Hibernate query criteria for join between 3 tables

2020-07-30 03:23发布

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.

2条回答
够拽才男人
2楼-- · 2020-07-30 03:55
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"));
查看更多
Viruses.
3楼-- · 2020-07-30 03:59

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();
查看更多
登录 后发表回答