我的实体类:
@Entity @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "USER_ID_GENERATOR", sequenceName = "USER_SEQ") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_ID_GENERATOR") @Column(name = "user_id") private long userId; @Temporal(TemporalType.DATE) private Date created; @Temporal(TemporalType.DATE) private Date modified; //setters and getters... }
我想在创建或修改对象时将CREATED和MODIFIED字段自动互补。CREATED和MODIFIED字段应为TIMESTAMP类型。
我该如何实现?
您只要在创建new Date()实例时就创建一个,然后updated在实体更新时就更新该字段:
new Date()
updated
private Date created = new Date(); private Date updated = new Date(); @PreUpdate public void setLastUpdate() { this.updated = new Date(); }
不要为这些方法中的任何一种提供设置器,仅提供获取器。