Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria Join with 3 Tables

I am looking for a hibernate criteria to get following:

Dokument.class is mapped to Role roleId

Role.class has a ContactPerson contactId

Contact.class FirstName LastName

I want to search for First or LastName on the Contact class and retrieve a list of Dokuments connected.

I have tried something like this:

session.createCriteria(Dokument.class) .setFetchMode("role",FetchMode.JOIN) .setFetchMode("contact",FetchMode.JOIN) .add(Restrictions.eq("LastName","Test")).list(); 

I get an error could not resolve property "LastName" for class "Dokument"

Can someone explain why the join searches on Dokument and not on all joined tables? Thanks in advance for all the help!

like image 972
mahatmanich Avatar asked Jan 04 '12 11:01

mahatmanich


People also ask

How can we join multiple tables in Hibernate criteria?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.

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.

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.


1 Answers

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument"); c.createAlias("dokument.role", "role"); // inner join by default c.createAlias("role.contact", "contact"); c.add(Restrictions.eq("contact.lastName", "Test")); return c.list(); 

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

like image 76
JB Nizet Avatar answered Sep 19 '22 18:09

JB Nizet