2017-01-02 31 views
-1

我再次必須請您幫助我完成我的項目。如何避免關係「我的父親是我的兒子」

我的關係類:

private GT_Member mother; 

private GT_Member father; 

private GT_Family ownerF; 

private List<GT_Member> children; 

我如何在Spring應用程序驗證親子實現?我想禁止一個人的父親或祖父爲他的兒子。

在客戶端lourd是簡單的情況,我做了過濾列表。但是它在數據庫中如何呢?

回答

1

創建一個addChild方法並遞歸地向上檢查層次結構以確保該子項不是其自己的祖先的一部分。

像這樣:

public class GT_Member { 

    private final GT_Member mother; 

    private final GT_Member father; 

    private final List<GT_Member> children; 

    public GT_Member(final GT_Member mother, final GT_Member father) { 
     this.mother = mother; 
     this.father = father; 
     this.children = new ArrayList<>(); 
    } 

    /** 
    * Add a child to this member. 
    * @param child 
    */ 
    public void addChild(GT_Member child) { 
     if (child == null) { 
      throw new IllegalArgumentException("Null children not allowed"); 
     } 
     if (child.equals(this)) { 
      throw new IllegalArgumentException("Can't add self as a child"); 
     } 
     if (isAncestor(child)) { 
      throw new IllegalArgumentException("Can't add an ancestor as a child"); 
     } 
     children.add(child); 
    } 

    /** 
    * Check if a member is an ancestor to this member. 
    * @param member 
    * @return True if the member is an ancestor, false otherwise 
    */ 
    private boolean isAncestor(final GT_Member member) { 
     // Check if the member is the mother or father 
     return member.equals(mother) || member.equals(father) 
       // Check if the member is an ancestor on the mother's side 
       || (mother != null && mother.isAncestor(member)) 
       // Check if the member is an ancestor on the father's side 
       || (father != null && father.isAncestor(member)); 
    } 
} 
+0

謝謝很多。就是這個。 – VANILKA

0

我會接近兩級檢查 1.應用程序代碼中的業務邏輯驗證。 2.數據庫觸發器確保不會創建/更新這種不一致的關係。

+0

我prefere做業務邏輯,因爲我也必須檢查我的表弟不是我的兒子,還是我的妻子是不是我的女兒.. etc.etc ... – VANILKA