问题
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