Hibernate Create Criteria to join the same table twice - tried 2 approach with 2 difference error

孤者浪人 提交于 2019-11-28 13:06:57

There is an old Hibernate bug HHH-879 on the problem of org.hibernate.QueryException: duplicate association path opened 2005 and still open...

Other issue is closed without solution HHH-7882

So the option 1) is rather not suitable.

But in the comments of the above bug an usefull workaround is mentioned using exists

So use twice sqlRestriction with exists and a correlated subquery filtering the propper category. You will get only companies connected to both categories.

crit.add( Restrictions.sqlRestriction( 
  "exists (select null from Company_Customercategory a where {alias}.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)",
  1, IntegerType.INSTANCE ) );
crit.add( Restrictions.sqlRestriction( 
  "exists (select null from Company_Customercategory a where {alias}.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)",
  6, IntegerType.INSTANCE ) );

This leads to the following query which provides the correct result

select this_.COMPANY_ID as COMPANY_ID1_2_0_, this_.COMPANY_NAME as COMPANY_NAME2_2_0_ 
from COMPANIES this_ 
where exists (select null from Company_Customercategory a 
              where this_.company_Id = a.company_Id and a.CUSTOMERCATEGORYID =  ?) and 
      exists (select null from Company_Customercategory a 
              where this_.company_Id = a.company_Id and a.CUSTOMERCATEGORYID = ?)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!