Friday, February 28, 2014

Automatic date stamping of Hibernate entities

That's what I was looking for today and I found it on Stackoverflow. You can do that with three elegant JPA annotations :

  • @PrePersist : automatically invoke the annoted method before persist the new entity
  • @PreUpdate : automatically invoke the annoted method before update the existing entity
  • @Temporal : very important to set the temporal type to timestamp. Otherwise, Hibernate could store date without hours, minutes and seconds (only day, month and year)

Enjoy Hibernate and JPA!!! (On small projects, this is always a pleasure. On large one, things are always different...)

Here is the example I found : 

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

public abstract class AbstractTimestampEntity {

    @Column(name = "created", nullable = false)
    private Date created;

    @Column(name = "updated", nullable = false)
    private Date updated;

    protected void onCreate() {
    updated = created = new Date();

    protected void onUpdate() {
    updated = new Date();
and have all your entities extend it, for instance:
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {

Display Javascript console logs with jsfiddle

Jsfiddle is mainly made to test javascript code in a web context (aka with HTML and CSS). But, if you just want to use is to test backend c...