Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

java - Last update timestamp with 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;
    }


}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...