Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last update timestamp with JPA

Tags:

java

jpa

I'm playing around a bit with JPA(Eclipselink to be specific). The below entity have a timestamp that's supposed to reflect whenever that entity was last updated.

What are the strategies for making JPA update that timestamp automatically every time this entity is changed ?

How would I go about if I also want a 'creation' timestamp, only set when the entity is first persisted, never allowed to be changed again ?

 @Entity
 public class Item implements Serializable {
     private static final long serialVersionUID = 1L;
     private Integer id;
     private String note;


    public Item () {
    }


    @Id
    @GeneratedValue(strategy=SEQUENCE)
    @Column(unique=true, nullable=false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }


    @Column(length=255)
    @Column(nullable=false)
    public String getNote() {
        return this.note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @Column(nullable=false)
    public Timestamp getUpdated() {
        return this.updated;
    }

    public void setUpdated(Timestamp updated) {
        this.updated = updated;
    }


}
like image 874
nos Avatar asked Nov 17 '09 00:11

nos


People also ask

How do you update a timestamp?

Syntax – Update value to Current TimestampALTER TABLE table_name updates table schema. CHANGE column_name updates the column to. column_name TIMESTAMP NOT NULL defines the column as of datatype TIMESTAMP. DEFAULT CURRENT_TIMESTAMP sets the default value of the column to CURRENT_TIMESTAMP.

What does@ CreationTimestamp do?

Annotation Type CreationTimestampMarks a property as the creation timestamp of the containing entity. The property value will be set to the current VM date exactly once when saving the owning entity for the first time.

What is @PrePersist in JPA?

The @PrePersist and @PreUpdate annotations are JPA annotations introduced in JPA 1.0. Both annotations are used to configure callbacks that are triggered on specific entity lifecycle events. The @PrePersist annotation is used to configure a callback for pre-persist(pre-insert) events of the entity.


1 Answers

Use @PrePersist and @PreUpdate annotations and write your own event listener.

Take a look at this answer for details. It's tagged as Hibernate but is applicable to any JPA provider.

like image 161
ChssPly76 Avatar answered Sep 22 '22 10:09

ChssPly76