我再次必须请您帮助我完成我的项目。如何避免关系“我的父亲是我的儿子”
我的关系类:
private GT_Member mother;
private GT_Member father;
private GT_Family ownerF;
private List<GT_Member> children;
我如何在Spring应用程序验证亲子实现?我想禁止一个人的父亲或祖父为他的儿子。
在客户端lourd是简单的情况,我做了过滤列表。但是它在数据库中如何呢?
我再次必须请您帮助我完成我的项目。如何避免关系“我的父亲是我的儿子”
我的关系类:
private GT_Member mother;
private GT_Member father;
private GT_Family ownerF;
private List<GT_Member> children;
我如何在Spring应用程序验证亲子实现?我想禁止一个人的父亲或祖父为他的儿子。
在客户端lourd是简单的情况,我做了过滤列表。但是它在数据库中如何呢?
创建一个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));
}
}
我会接近两级检查 1.应用程序代码中的业务逻辑验证。 2.数据库触发器确保不会创建/更新这种不一致的关系。
我prefere做业务逻辑,因为我也必须检查我的表弟不是我的儿子,还是我的妻子是不是我的女儿.. etc.etc ... – VANILKA
谢谢很多。就是这个。 – VANILKA