Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I left join a subquery in hibernate with criteria?

Tags:

java

hibernate

I want to be able to left join a subquery in hibernate with criteria.

Here is sample query:

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')

Note this is a sample query, mine is more complex and I need to be able to left join a subquery.

How could you generate this query with the hibernate criteria syntax?

I would like to do something similar to this:

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();

Edit

In my real problem the subquery consists of two tables.

like image 989
Jakob Avatar asked Oct 15 '25 04:10

Jakob


1 Answers

You can use createAlias API of Criteria class and specify join type. Refer this documentation for more details.

    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.
like image 113
Atul Avatar answered Oct 17 '25 17:10

Atul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!