2017-04-10 66 views
0

我有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; 
    } 
} 
+1

用戶EntityListeners爲您的回調攔截: https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en /html/listeners.html – fangdi

+0

我在persistence.xml中有2個持久單元。如何配置它們以對GenericEntity類使用不同的EntityListeners? – Justas

回答

1

如果你給訪問設置創造價值(由二傳手),你不應該在@PrePersist方法覆蓋此值。我認爲,解決這個問題最簡單的方法是簡單的空檢查:

@PrePersist 
protected void onCreate() { 
    if (created == null) { 
     created = new Date(); 
    } 
} 
+0

只是==而不是!= – Justas

+0

是的,我的錯誤:) –