How to auto insert Current DATE in SQL with Java / Hibernate
36,720
Solution 1
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.
Solution 2
While Emil H is correct, I would like to add that way you did should work too.
It didn't most likely because the name of the column (you said in comment it is "date") doesn't match name of the field ("dateoperation").
You could either rename field/column, or add annotation:
@Column(name = "date")
Also note: you don't have to use java.sql.Date, it should work with java.util.Date just as well.
import java.util.Date;
...
@Column(name = "date")
private Date dateoperation = new Date();
Solution 3
For create, you need to use:
@CreationTimestamp
@Generated(GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateoperation = new java.sql.Date(new java.util.Date().getTime());
Comments
-
socrateisabot about 3 years
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;