2016-02-06 32 views
1

是否有可能在hibernate在其中你有兩個領域,其中任何可能爲空,但至少一個用例模型他們不能爲空?下面是我此刻的代碼,但我不喜歡這樣的事實,我有他們兩個設置爲@Column(nullable = true)。在我來說,我想無論是個人電子郵件地址或工作地址。有沒有一種好的方法來支持這個?還是需要一種替代方法?休眠 - 無論是場A或B可以爲空,但A的一個或B不能爲空

public class ApplicantDetails { 

    //... 

    @OneToOne(optional = false) 
    private ContactDetails contactDetails; 

    //... 
} 

public class ContactDetails { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer id; 

    /*Need at least one email address but it doesn't matter which one.*/ 
    @Column(nullable = true, unique = true) 
    private String personalEmail; 

    @Column(nullable = true, unique = true) 
    private String workEmail; 

    //... 

} 
+0

看看按位異或運算[http://stackoverflow.com/questions/1991380/what-does-the-operator-do -in-java的(http://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java) –

+0

@leviClouser怎麼會在這裏幫助? –

回答

0

我會建議,如果你的數據庫支持某種形式的它,你反正在數據庫中定義一個CHECK約束:

CHECK (PERSONAL_EMAIL IS NOT NULL OR WORK_EMAIL IS NOT NULL) 

對於中間層,可以簡單的寫在服務自己的驗證那家商店/更新ContactDetails並提高相應的例外情況,如果試圖存儲/更新不一致的狀態是由,或者您可以使用驗證框架像Hibernate validator

一個快速的解決方法也可以利用實體​​生命週期回調方法:

@PrePersist 
@PreUpdate 
private void validate() { 
    if (personalEmail == null && workEmail == null) { 
    throw new ValidationException(); 
    } 
} 
相關問題