冬眠的标准查询自引用实体;结果不正确



我有一个自我引用实体Department,它可以具有孩子Departments(n级深)。Hibernate标准查询似乎感到困惑。它正确地创建了树,因为所有父母都有正确的孩子,但是它也任意将孩子直接放在祖父母的范围下,因此,祖父母最终生了孩子(正确),而孩子的孩子(不正确)它。

有一个顶级实体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;
}
}

lob:

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;
}
}

Hibernate标准查询:

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();

我不确定我是否已映射了自我引用协会的权利。任何帮助将不胜感激。

您已经映射了以这种方式设置的部门,以使所有引用LOB的部门都在集合中,但整个树都引用了相同的LOB,不仅是顶部。因此,您必须将该限制添加到集合映射中。使用冬眠将是

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

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

最新更新