thanks to you guys my knowlegde on hibernate has been improve dratiscally. now i hit a block here about current_timestamp. here is my codes
@Column(name="DATE_CREATED", insertable=false, updatable=false, columnDefinition="timestamp default current_timestamp")
@org.hibernate.annotations.Generated(value=GenerationTime.INSERT)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date dateCreated;
@Column(name="LAST_MODIFIED", insertable=false, updatable=false, columnDefinition="datetime")
@org.hibernate.annotations.Generated(value=GenerationTime.ALWAYS)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date lastModified;
i want date_created to get the current_timestamp and i want the lastmodified to insert the time for each updates.apparently i can't have 2 current_timestamp fields on the same table.Is there other ways to achieve that? thanks for reading
@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.
JPA specifies seven optional lifecycle events that are called: before persist is called for a new entity – @PrePersist. after persist is called for a new entity – @PostPersist. before an entity is removed – @PreRemove. after an entity has been deleted – @PostRemove.
The @Column annotation is defined as a part of the Java Persistence API specification. It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.
This is not related to Hibernate per se. Your annotations as specified above tell Hibernate that the values are going to be generated by the database and thus need to be reloaded after entity is inserted / updated.
If that's the way you want to go with, you need to configure your database (by creating a trigger, for example) to populate date_created
/ last_modified
columns as needed.
Another approach is to not mark those fields as generated and instead update them in your java code. If you're using JPA (via Hibernate EntityManager), it's rather trivial to do this via @PrePersist / @PreUpdate callback method:
@PreUpdate
@PrePersist
public void updateTimeStamps() {
lastModified = new Date();
if (dateCreated==null) {
dateCreated = new Date();
}
}
You could achieve the same thing with hibernates @CreationTimestamp
and @UpdateTimestamp
annotations e.g.
@Column(name = "CREATED")
@CreationTimestamp
private LocalDateTime created;
@Column(name = "LAST_UPDATED")
@UpdateTimestamp
private LocalDateTime lastUpdated;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With