自我引用实体的Hibernate Criteria查询;结果不正确

时间:2012-11-05 16:05:08

标签: hibernate jpa hibernate-criteria

我有一个自引用实体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;
}
}

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 Criteria Query:

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

我不确定我是否已将自引用关联映射到右侧。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您已经映射了Departments集,其方式是引用Lob的所有Departments都在集合中,但整个树引用相同的Lob而不仅仅是顶部。因此,您必须将该限制添加到集映射。使用hibernate将是

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

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