1

我有一个自引用实体 ,Department它可以有子实体Departments(n 级深)。Hibernate Criteria Query 似乎变得混乱。它正确地创建了树,因为所有父母都有正确的孩子,但是它也任意将孩子直接放在祖父母之下,所以祖父母最终有它的孩子(这是正确的)和孩子的孩子(不正确)直接在下面它。

有一个顶级实体Organization,其下可以有 n 个LoB实体。Lob 代表业务线。在每个之下都有一个实体LoB层次结构。Department

组织:

public class Organization {
    ...
private Set<Lob> lobs = new HashSet<Lob>();

@OneToMany(mappedBy = "organization", cascade = { CascadeType.PERSIST,
        CascadeType.MERGE, CascadeType.REMOVE })
public Set<Lob> getLobs() {
    return lobs;
}

public void setLobs(Set<Lob> lobs) {
    this.lobs = lobs;
}
}

高球:

public class Lob {
...
private Long id;    
private Organization organization;
private Set<Department> departments = new HashSet<Department>();

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ORG_ID", nullable = false)
public Organization getOrganization() {
    return organization;
}

public void setOrganization(Organization organization) {
    this.organization = organization;
}

@OneToMany(mappedBy = "lob", cascade = { CascadeType.PERSIST,
        CascadeType.MERGE, CascadeType.REMOVE })
public Set<Department> getDepartments() {
    return departments;
}

public void setDepartments(Set<Department> departments) {
    this.departments = departments;
}
}

部门:

public class Department {
...
private Set<Department> children = new HashSet<Department>();
private Department parent;
private Lob lob;

@OneToMany(mappedBy = "parent")
public Set<Department> getChildren() {
    return children;
}

public void setChildren(Set<Department> children) {
    this.children = children;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PARENT_ID") 
public Department getParent() {
    return parent;
}

public void setParent(Department parent) {
    this.parent = parent;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "LOB_ID")
public Lob getLob() {
    return lob;
}

public void setLob(Lob lob) {
    this.lob = lob;
}
}

休眠条件查询:

Session session = (Session) getEntityManager().getDelegate();
Criteria crit = session.createCriteria(Organization.class);

// Get the whole Org tree
org = (Organization) crit.createAlias("lobs", "l", Criteria.LEFT_JOIN)
    .setFetchMode("l", FetchMode.JOIN)
    .createAlias("l.departments", "d", Criteria.LEFT_JOIN)
    .setFetchMode("d", FetchMode.JOIN)
    .createAlias("d.children", "dc", Criteria.LEFT_JOIN)
    .setFetchMode("dc", FetchMode.JOIN)
    .add(Restrictions.eq("id", orgId))                                      
    .uniqueResult();

我不确定我是否正确映射了自引用关联。任何帮助将不胜感激。

4

1 回答 1

0

您已经映射了部门集,即所有引用 Lob 的部门都在集合中,但整个树不仅引用了顶部,还引用了同一个 Lob。因此,您必须将该限制添加到集合映射中。使用休眠它会是

<set name="departments" where="parent_id IS NULL">
  <key column="LOB_ID" />
  <one-to-many class="Department" />
</set>

也许其他人可以编辑添加相应的注释

于 2012-11-07T09:57:53.197 回答