Search code examples
javasqlhibernatedateannotations

How to auto insert Current DATE in SQL with Java / Hibernate


I need to add automatically the current date into my Database when I create a new OperantionBank. I'm using Hibernate. Thanks

import java.io.Serializable;
import java.sql.Date;
import javax.persistence.*;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

@Entity
public class OperationBank implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String wordring;

private Double amount;

@Generated(GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateoperation = new java.sql.Date(new java.util.Date().getTime());

@OneToOne
private Account account;

Solution

  • This answer might help you:

    https://stackoverflow.com/a/221827/355499

    In essence you use @PrePersist and/or @PreUpdate annotation to generate the dates when needed.