Hibernate Criteria Join with 3 Tables

元气小坏坏 提交于 2019-11-26 03:09:07

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/8726396/hibernate-criteria-join-with-3-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!