Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

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!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...