使用 Hibernate Criteria API 查询与投影的多对一关系
我尝试在以下场景中使用 Criteria API:
- 我有两个表,
Schedule
和Route
(及其类和映射)。 -
Route
与Schedule
具有多对一关系。 -
Route
有一个整数属性sequence
。
现在我需要获取所有那些关联 Route 对象满足以下条件的 Schedule 对象:
route.sequence=no. of all Route objects associated with the given Schedule object
我已为其尝试了以下 Criteria 代码:
Criteria crit = getSession().createCriteria(getPersistentClass())
.createCriteria("routes", "route")
.setProjection(Projections.projectionList()
.add( Projections.rowCount(), "routeCount"))
.add(Restrictions.not(Restrictions.ltProperty("route.sequence", "routeCount")));
但它生成以下 sql:
select count(*) as y0_
from schedule this_
inner join route route1_ on this_.ID=route1_.scheduleId
where route1_.sequence<y0_
并抛出以下错误:
Unknown column 'y0_' in 'where clause'
如果您有任何建议,请帮助我。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题源于预测和限制的实施问题。尝试在同一列上进行投影和限制时似乎存在错误 - 生成的 sql 无效。您会发现,如果直接针对数据库运行该 sql,它将无法工作。
该错误最初记录在此处,看起来不会固定的。但后来我看到此处记录了另一个类似的错误,但我可以'无法确定修复程序将在哪个版本中提供。
可以找到更多涉及该问题及其背后理论的讨论 此处。
还有另一个处理相同问题的stackoverflow项目和提供了一个解决方案。我还没有尝试过这种方法是否有效,但它似乎对涉及该问题的人有效。
The problem stems from an implementation issue with projections and restrictions. It seemed that there was a bug when trying to project and restrict on the same column - the generated sql was not valid. You will find that if run that sql directly against your database that it won't work.
The bug was originally logged here and it looked like it would not be fixed. But then I see another similar bug was logged here but I can't work out which release the fix will be available in.
The discussion that deals more with the issue and the theory behind it can be found here.
There is also another stackoverflow item dealing with the same question and offers a solution. I haven't tried to see if this approach works but it seemed to work for the people involved in the issue.