Hibernate Criteria API: Joining tables with custom join

criteria, hibernate, join

Solution

You will probably need to use the createAlias or the createCriteria method.

public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException;

public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException;

There is a forum discussion that will help you: https://hibernate.onjira.com/browse/HHH-2308

For example:

Criteria criteria = getSession().createCriteria(Table_a.class);
criteria.addAlias("Table_b","joined_alias",CriteriaSpecification.LEFT_JOIN);
criteria.list();

Problem

I am asking myself if following query can be mapped by Hibernate Criteria API ``` SELECT * FROM table_a as a LEFT OUTER JOIN table_b as b ON a.primary_key = b.foreign_key and b.any_column = 'my_value' ``` Ok, everything except `and b.any_column = 'my_value'` is not difficult for me. Either using FetchMode.JOIN or addCriteria(...,...). But the `and b.any_column = 'my_value'` is producing headaches. I have tried with embedding: ``` addCriteria("b", Criteria.LEFT_JOIN).add(Restriction.eq("b.any_column", my_value)) ``` But this is producing: ``` SELECT * FROM table_a as a LEFT OUTER JOIN table_b as b ON a.primary_key = b.foreign_key WHERE b.any_column = 'my_value' ``` This is not my purpose and is of course producing different results then my expected query. Can anybody give me a hint how I can tell Hibernate to map to the desired query? Thanks, Michael

Original source