问题:当我将实体集合字段作为HQL语句的一部分引用时,HQL查询未返回任何结果。它适用于一个HQL投影,例如:
select inc.categoryTypes as categoryTypes from IncidentEntity inc where (inc.id = :id105019)
categoryTypes是IncidentEntity类字段之一(它是定义为ManyToMany连接的集合,如下所示)。这工作正常,但是当我尝试引用另一个映射为ManyToMany连接的投影集合时会出现问题。
select inc.categoryTypes as categoryTypes, inc.consequences as consequences from IncidentEntity inc where (inc.id = :id105019)
一旦我这样做,我得到一个空集。这意味着hibernate生成的SQL查询不会返回任何内容。我已经通过在SQL管理器中执行该命令来验证这一点,该命令不返回任何结果。
这是IncidentEntity:
/**
* Database entity for the 'incidents' table records.<br>
* Entity domain object is {@link nz.co.doltech.ims.shared.domains.Incident}
* @author Ben Dol
*
*/
@javax.persistence.Entity(name = "incidents")
@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class IncidentEntity implements Entity {
...
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "incident_categorytype", joinColumns = {
@JoinColumn(name = "incident_id") },
inverseJoinColumns = {
@JoinColumn(name = "categorytype_id")
})
private Set<CategoryTypeEntity> categoryTypes = new HashSet<CategoryTypeEntity>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "incident_consequence", joinColumns = {
@JoinColumn(name = "incident_id") },
inverseJoinColumns = {
@JoinColumn(name = "consequence_id")
})
private Set<ConsequenceEntity> consequences = new HashSet<ConsequenceEntity>();
...
public Set<CategoryTypeEntity> getCategoryTypes() {
return categoryTypes;
}
public void setCategoryTypes(Set<CategoryTypeEntity> categoryTypes) {
this.categoryTypes = categoryTypes;
}
public Set<ConsequenceEntity> getConsequences() {
return consequences;
}
public void setConsequences(Set<ConsequenceEntity> consequences) {
this.consequences = consequences;
}
...
}
CategoryTypeEntity关系定义:
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "categoryTypes")
private Set<IncidentEntity> incidents = new HashSet<IncidentEntity>();
ConsequenceEntity关系定义:
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "consequences")
private Set<IncidentEntity> incidents = new HashSet<IncidentEntity>();
数据结构:
使用 Hibernate 3.6.10
也许我设置了错误的定义,或者我在这里错过了HQL的限制,我不确定。非常感谢我能得到的任何帮助。谢谢!
此致 本
答案 0 :(得分:1)
您知道使用此查询生成笛卡尔积,对吗?
查询可以更好地显示为:
select categoryTypes, consequences
from IncidentEntity inc
inner join inc.categoryTypes as categoryTypes
inner join inc.consequences as consequences
where (inc.id = :id105019)
因为您尚未指定显式连接,所以假定INNER JOIN不是LEFT JOIN。
我们假设指定事件有类别。因此,此查询将返回此事件的类别,这也是您报告的内容:
select categoryTypes
from IncidentEntity inc
inner join inc.categoryTypes as categoryTypes
where (inc.id = :id105019)
但是当没有后果时,INNER JOIN将不会返回任何结果,所以:
select categoryTypes, consequences
from IncidentEntity inc
inner join inc.consequences as consequences
where (inc.id = :id105019)
不会返回任何内容,但您的查询也会发生这种情况:
select categoryTypes, consequences
from IncidentEntity inc
inner join inc.categoryTypes as categoryTypes
inner join inc.consequences as consequences
where (inc.id = :id105019)