我希望能够使用条件在hibernate中加入子查询。
以下是示例查询:
Select * From Order o
Left Join (Select * From Product p Where p.accountId = 3) p
On p.id = o.productId
Where (p.category is not null and p.category = 'clothes') or
(p.category is null and o.category = 'clothes')
注意这是一个示例查询,我的更复杂,我需要能够加入子查询。
我想做类似的事情:
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Order.class);
DetachedCriteria productCriteria = DetachedCriteria.forClass(Product.class);
productCriteria.add(Restrictions.eq("accountId", 3));
criteria.createAlias("productCriteria", "p", JoinType.LEFT_OUTER_JOIN, productCriteria);
criteria.add(Restrictions.or(
Restrictions.and(Restrictions.isNotNull("p.category"), Restrictions.eq("p.category", "clothes")),
Restrictions.and(Restrictions.isNull("p.category"), Restrictions.eq("category", "clothes"))
));
List list = criteria.list();
在我的实际问题中,子查询由两个表组成。
答案 0 :(得分:1)
您可以使用Criteria类的createAlias API并指定连接类型。 有关详细信息,请参阅this文档。
Criteria createAlias(String associationPath,
String alias,
int joinType)
throws HibernateException
Join an association using the specified join-type, assigning an alias to the joined association.
The joinType is expected to be one of CriteriaSpecification.INNER_JOIN (the default), CriteriaSpecification.FULL_JOIN, or CriteriaSpecification.LEFT_JOIN.