【发布时间】:2019-07-21 22:11:30
【问题描述】:
我想为以下原生 sql 创建创建条件。
不幸的是,我在两次使用 createCriteria 时遇到了重复关联路径的错误。 当我尝试使用 Restrictions.sqlRestriction。它无法提供我想要的 SQL。
尝试 1:创建标准 - 重复关联路径
Criteria criteria = getSession().createCriteria( Company.class );
criteria.createAlias( "customerCategories", "c1" );
criteria.add( Restrictions.in( "c1.customerCategory.customerCategoryId",
company.getBaseCustomerCategoryId() ) );
criteria.createAlias( "customerCategories", "c2" );
criteria.add( Restrictions.in( "c2.customerCategory.customerCategoryId",
company.getPromoCustomerCategoryId() ) );
尝试 2:创建 SQL 限制 - ORA-00920:由于“where”,关系运算符无效
Criteria criteria = getSession().createCriteria( Company.class );
criteria.add( Restrictions.sqlRestriction(
"INNER JOIN Company_Customercategory a on {alias}.companyId = a.companyId and a.CUSTOMERCATEGORYID = ?",
company.getBaseCustomerCategoryId(), LongType.INSTANCE ) );
criteria.add( Restrictions.sqlRestriction(
"1=1 INNER JOIN Company_Customercategory b on {alias}.companyId = b.companyId
and b.CUSTOMERCATEGORYID = ?",
company.getPromoCustomerCategoryId(), LongType.INSTANCE) );
错误的结果
select this_.* from Companies this_ where
INNER JOIN Company_Customercategory a
on this_.companyId = a.companyId
and a.CUSTOMERCATEGORYID = 1
and 1=1 INNER JOIN Company_Customercategory b
on this_.companyId = b.companyId
and b.CUSTOMERCATEGORYID = 6
预期的 SQL
select * from companies c
inner join Company_Customercategory a
on c.companyId = a.companyId
and a.CUSTOMERCATEGORYID = 1
inner JOIN Company_Customercategory b
on a.companyId = b.companyId
and b.CUSTOMERCATEGORYID = 6
感谢您的帮助。 谢谢。
【问题讨论】:
-
如何从原生sql转换为使用criteria?
-
发布实体源代码。阅读如何正确发布问题:stackoverflow.com/help/mcve
标签: sql oracle hibernate criteria