64

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!

mahatmanich
  • 10,276
  • 5
  • 57
  • 79

1 Answers1

125

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.

Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
  • 3
    JB thanks so much. Yeah I have read the specs, but for a Hibernate newbee it is quite hard to wrap one's head around all the Hibernate lingo. Again THANKS IT WORKS :-) – mahatmanich Jan 04 '12 at 12:34
  • btw what is an association, just some reference? – mahatmanich Jan 04 '12 at 12:34
  • An association is when an entity is linked to another entity with a OneToOne, OneToMany, ManyToOne or ManyToMany... association. – JB Nizet Jan 04 '12 at 13:05
  • 38
    @JBNizet I would argue that the reference manual does not explain well. Unless you're better than me at relating cats and kittens to business objects. – cbmeeks Nov 09 '12 at 21:54
  • @JBNizet, I wonder if I can ask you for help on this particualr question. http://stackoverflow.com/questions/17653399/hibernate-many-to-many-data-retrival-via-query?noredirect=1#comment25714062_17653399 – Harbir Jul 16 '13 at 07:06
  • @JBNizet could you please look at my problem [How to write HQL JOIN query for multiple table's selected Columns using Constructor In The Select Clause](https://stackoverflow.com/q/47726605/3425489), **thank you** – Shantaram Tupe Dec 09 '17 at 09:39
  • After 10 years of using Hibernate, I finally found this, which helped me forward. Thanks :) – Thor Hovden May 06 '22 at 12:41