Hibernate 标准左连接两个表
我有两个实体,即“业务”和“区域”。
相关属性:
业务 - 区域、区域2、代码
区域 - 业务的areaId、areaName
区域和area2映射到区域中的id
我正在尝试编写一个Hibernate标准,该条件仅返回所有包含企业的区域。
SQL 看起来像: FROM 区域 a LEFT OUTER JOIN 业务 b on a.areaId = b.area 或 a.areaId = b.area2 WHERE b.code != null GROUP BY a.areaName
这就是我所拥有的:
DetachedCriteria criteria = DetachedCriteria.forClass(Business.class)
.setProjection(Property.forName("area"))
.setProjection(Property.forName("area2"))
.add(Restrictions.ne("code", null));
Criteria criteriaArea = fullTextSession.createCriteria(Area.class)
.createAlias("areaId", "areaId", CriteriaSpecification.LEFT_JOIN)
.add(Property.forName("areaId").in(criteria));
但这不起作用,我收到“不是关联:areaId”查询异常。
有什么想法为什么会发生这种情况吗?谢谢。
I have two entities, say Business and Area.
Relevant properties:
Business - area, area2, code
Area - areaId, areaName
area and area2 of Business map to the id in Area
I'm trying to write a Hibernate criteria that returns all the areas with businesses only.
SQL looks like:
FROM area a LEFT OUTER JOIN business b on a.areaId = b.area or a.areaId = b.area2
WHERE b.code != null
GROUP BY a.areaName
This is what I have:
DetachedCriteria criteria = DetachedCriteria.forClass(Business.class)
.setProjection(Property.forName("area"))
.setProjection(Property.forName("area2"))
.add(Restrictions.ne("code", null));
Criteria criteriaArea = fullTextSession.createCriteria(Area.class)
.createAlias("areaId", "areaId", CriteriaSpecification.LEFT_JOIN)
.add(Property.forName("areaId").in(criteria));
But this doesn't work, I get a "not an association: areaId" query exception.
Any ideas why this is happening? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
createAlias()
使用提供的属性加入另一个实体。 Hibernate 使用提供的属性映射来计算要连接的表。但areaId
未映射为对业务实体的@ManyToOne
或@ManyToMany
引用。所以 Hibernate 不明白你想使用 Area.areaId 加入哪个表。您的条件将被转换为 SQL,如下所示:
您可以重写查询而不使用未使用的连接:
createAlias()
joins another entity using provided property. Hibernate calculates what table to join using mapping of provided property. ButareaId
isn't mapped as a@ManyToOne
or@ManyToMany
reference to Business entity. So Hibernate doesn't understand to what table you want to join using Area.areaId.Your criteria will be translated to SQL like:
You may rewrite query without unused join: