Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate criteria: Joining table without a mapped association

I'd like to use Hibernate's criteria api to formulate a particular query that joins two entities. Let's say I have two entities, Pet and Owner with a owner having many pets, but crucially that association is not mapped in the Java annotations or xml.

With hql, I could select owners that have a pet called 'fido' by specifying the join in the query (rather than adding a set of pets to the owner class).

Can the same be done using hibernate criteria? If so how?

Thanks, J

like image 435
Snukker Avatar asked Apr 06 '09 07:04

Snukker


People also ask

How do you join tables in hibernate?

We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table's primary key as a child table's foreign key.

Can you perform joins in hibernate?

Hibernate provides support for join statements where one can write single query to fetch data from multiple tables easily.


2 Answers

This is indeed possible with criteria:

DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class); ownerCriteria.setProjection(Property.forName("id")); ownerCriteria.add(Restrictions.eq("ownername", "bob"));  Criteria criteria = getSession().createCriteria(Pet.class); criteria.add(Property.forName("ownerId").in(ownerCriteria)); 

Update: This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined.

like image 76
Pierre Pretorius Avatar answered Oct 17 '22 14:10

Pierre Pretorius


My understanding is that if you do this using HQL, you are creating a Cartesian join with a filter, rather than an inner join. Criteria queries do not support doing this.

like image 28
David M Avatar answered Oct 17 '22 12:10

David M