我有GenericEntity
類@PrePersist
方法onCreate()
它設置時間戳就在將實體保存到數據庫之前。它運行良好,但是當我嘗試測試我的DAO類時,我遇到了問題。 @PrePersist
在保存實體時明確設置created
字段值。如何在測試環境中使@PrePersist可選,以便我可以明確設置created
字段值?JPA @PrePersist在測試環境中
@MappedSuperclass
public abstract class GenericEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", nullable = false)
private Date created;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@PrePersist
protected void onCreate() {
created = new Date();
}
/*
* Used for tests
*/
public void setCreated(Date created) {
this.created = created;
}
public Date getCreated() {
return created;
}
}
用戶EntityListeners爲您的回調攔截: https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en /html/listeners.html – fangdi
我在persistence.xml中有2個持久單元。如何配置它們以對GenericEntity類使用不同的EntityListeners? – Justas