1
我使用的是基礎機構:JPA PrePersist和更新前
@MappedSuperclass
public class BaseEntity {
private static final Logger L = LoggerFactory.getLogger(BaseEntity.class);
String id;
String name;
String description;
Date created;
Date updated;
public BaseEntity() {
id = UUID.randomUUID().toString();
}
@PrePersist
protected void onCreate() {
created = new Date();
}
@PreUpdate
protected void onUpdate() {
updated = new Date();
}
@Id
@Column(name = "id", nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
... snip
然後,我有一個實體:
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property = "@baby_id", scope = Baby.class)
@Table(name="babies")
public class Baby extends BaseEntity {
private static final Logger L = LoggerFactory.getLogger(Baby.class);
Date dob;
public Baby() {
super();
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
... snip ...
這裏是我的測試:
@Test
@Transactional
public void testCreateBaby() {
Baby b = new Baby();
b.setName("n");
b.setDescription("baby");
b.setDob(new Date());
assertNull(b.getCreated());
assertNull(b.getUpdated());
em.persist(b);
assertNotNull(b);
assertNotNull(b.getCreated());
assertNull(b.getUpdated());
b.setName("n3");
b = em.merge(b);
em.persist(b);
assertNotNull(b.getUpdated());
}
測試失敗因爲updated
字段沒有設置。我該怎麼做呢?這是Hibernate JPA,用於測試的是arquillian和wildfly。
嘗試強制刷新。可能是直到刷新之前才執行回調。 –
[@PreUpdate和@Prepersist在hibernate/JPA(使用會話)中可能有重複](http://stackoverflow.com/questions/4133287/preupdate-and-prepersist-in-hibernate-jpa-using-session) – sauumum
請請參閱http://forum.spring.io/forum/spring-projects/data/46235-hibernate-3-2-persistent-lifecycle-annotations-notwork,如果它有幫助 – sauumum