假设我们有3个实体
<class name="AEntity" table="A" abstract="true">
<id name="id">
<column name="ID"/>
</id>
<joined-subclass table="Aa" name="AaEntity">
<key column="key"/>
<many-to-one name="b" class="BEntity">
<column name="B_ID"/>
</many-to-one>
</joined-subclass>
<joined-subclass table="Ab" name="AbEntity">
<key column="key"/>
<many-to-one name="b" class="BEntity">
<column name="B_ID"/>
</many-to-one>
</joined-subclass>
</class>
<hibernate-mapping>
<class name="Parent" table="parent">
<id name="id">
<column name="ID"/>
</id>
<many-to-one name="a" class="AEntity">
<column name="a_ID" />
</many-to-one>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="BEntity" table="B">
<id name="id">
<column name="ID"/>
</id>
</class>
</hibernate-mapping>
然后,我们制定标准请求
Criteria criteria = session.createCriteria(Parent.class);
criteria.createAlias("a","a");
criteria.createAlias("a.b","b");
criteria.list();
然后获取下一个sql
select this_.ID as ID1_5_3_,
this_.a_ID as a2_5_3_,
a1_.ID as ID1_2_0_,
a1_.B_ID as B2_2_0_,
a1_1_.B_ID as B2_0_0_,
a1_2_.B_ID as B2_1_0_,
case when a1_1_.key is not null then 1 when a1_2_.key is not null then 2 when a1_.ID is not null then 0 end as clazz_0_,
b2_.ID as ID1_3_1_,
b2_.C_ID as C2_3_1_,
b2_.ID as ID1_3_2_,
b2_.C_ID as C2_3_2_
from parent this_
inner join A a1_ on this_.a_ID=a1_.ID
left outer join Aa a1_1_ on a1_.ID=a1_1_.key
left outer join Ab a1_2_ on a1_.ID=a1_2_.key
inner join B b2_ on a1_1_.B_ID=b2_.ID
inner join B b2_ on a1_2_.B_ID=b2_.ID
我们可以看到B表连接两次并且具有相同的名称b2_。是bug吗?如何使两个连接但具有不同的B表名称。 好吗?
答案 0 :(得分:0)
尝试像
这样的别名Criteria criteria = session.createCriteria(Parent.class, "parent");
criteria.createAlias("parent.a","a");
criteria.createAlias("parent.a.AaEntity.b","aab");
criteria.createAlias("parent.a.AbEntity.b","abb");
criteria.list();
PS:我没有对此进行测试,它可能无法正常工作,但这会让您了解如何强制使用别名。