Hibernate query criteria for join between 3 tables

廉价感情. 提交于 2020-01-13 06:54:11

问题


I have a sql query:

select * from A
INNER JOIN B
ON A.id = B.id
INNER JOIN C
ON B.id = C.id
INNER JOIN D
ON C.id = D.id
where D.name = 'XYZ'
   and D.Sex = 'M'

I have been trying to come with hibernate query criteria for the above sql, but having problems. Could anybody help out.


回答1:


Criteria c = session.createCriteria(A.class, "a");
                    .createAlias("a.b", "b")
                    .createAlias("b.c", "c")
                    .createAlias("c.d", "d")
                    .add(Restrictions.eq("d.sex", "M"))
                    .add(Restrictions.eq("d.name", "XYZ"));



回答2:


On your question you want to perform a Cartesian Join, and this is not supported by Criteria, although you can do it with HQL as show below. There is a similar question here

With HQL query you could do something like:

select a from 
   A a, 
   B b, 
   C c 
where 
   a.id = b.id and 
   c.id = b.id and 
   d.id = c.id and 
   d.name = 'XYZ' and 
   d.sex = 'M'

The query is used in a regular hibernate query:

Query query = session.createQuery(query); // <-- here you use the query above
List results = query.list();


来源:https://stackoverflow.com/questions/11334743/hibernate-query-criteria-for-join-between-3-tables

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