简体   繁体   English

使用Hibernate Criteria API查询与投影的多对一关系

[英]Using Hibernate Criteria API To Query Many-To-One Relationships with Projections

I am trying to use Criteria API in following scenario: 我正在尝试在以下情况下使用Criteria API:

  • I have two tables, Schedule and Route (with their classes and mappings). 我有两个表, ScheduleRoute (及其类和映射)。
  • Route has many-to-one relationship with Schedule . RouteSchedule有多对一的关系。
  • Route has an integer property sequence . Route具有整数属性sequence

Now I need to fetch all those Schedule objects whose associated Route objects fulfill the following condition: 现在,我需要获取所有与之关联的Route对象满足以下条件的Schedule对象:

route.sequence=no. of all Route objects associated with the given Schedule object

I have tried the following Criteria code for it: 我已经尝试过以下标准代码:

Criteria crit = getSession().createCriteria(getPersistentClass())
    .createCriteria("routes", "route")
    .setProjection(Projections.projectionList()
    .add( Projections.rowCount(), "routeCount"))
    .add(Restrictions.not(Restrictions.ltProperty("route.sequence", "routeCount")));

But it generates the following sql: 但是它会生成以下sql:

select count(*) as y0_ 
from schedule this_
inner join route route1_ on this_.ID=route1_.scheduleId
where route1_.sequence<y0_

and throws the following error: 并引发以下错误:

Unknown column 'y0_' in 'where clause'

Please help me if you have any suggestions. 如果您有任何建议,请帮助我。

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. 试图在同一列上进行投影和限制时似乎出现了一个错误-生成的sql无效。 You will find that if run that sql directly against your database that it won't work. 您会发现,如果直接针对您的数据库运行该sql,它将无法正常工作。

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. 还有另一个stackoverflow项目处理相同的问题并提供解决方案。 I haven't tried to see if this approach works but it seemed to work for the people involved in the issue. 我尚未尝试查看此方法是否有效,但它似乎对涉及此问题的人员有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM