Hibernate Criteria 连接 3 个表 [英] Hibernate Criteria Join with 3 Tables
问题描述
我正在寻找一个休眠条件来获得以下内容:
I am looking for a hibernate criteria to get following:
文档.class映射到角色角色 ID
Dokument.class is mapped to Role roleId
角色.class有一个联系人联系方式
Role.class has a ContactPerson contactId
联系人.class名姓氏
Contact.class FirstName LastName
我想在 Contact 类中搜索 FirstName 或 LastName 并检索连接的 Dokuments 列表.
I want to search for First or LastName on the Contact class and retrieve a list of Dokuments connected.
我尝试过这样的事情:
session.createCriteria(Dokument.class)
.setFetchMode("role",FetchMode.JOIN)
.setFetchMode("contact",FetchMode.JOIN)
.add(Restrictions.eq("LastName","Test")).list();
我收到一个错误,无法解析类Dokument"的属性LastName"
I get an error could not resolve property "LastName" for class "Dokument"
有人可以解释为什么连接在 Dokument 上搜索而不是在所有连接表上搜索吗?在此先感谢您的帮助!
Can someone explain why the join searches on Dokument and not on all joined tables? Thanks in advance for all the help!
推荐答案
fetch 模式只说必须要获取关联.如果要对关联实体添加限制,则必须创建别名或子标准.我通常更喜欢使用别名,但 YMMV:
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();
这当然在 Hibernate 参考手册,以及 javadoc for Criteria 甚至有例子.阅读文档:它有很多有用的信息.
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.
这篇关于Hibernate Criteria 连接 3 个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!