在子查询上使用DetachedCriteria返回所有字段

时间:2014-08-26 12:13:17

标签: hibernate jpa

我有以下需要转换为Criteria的查询

SELECT t1.id, t1.name, t2.desc, t3.date from
(SELECT * FROM a, b, c where a.id = b.id and b.id = c.id) t1
left join t2 on t1.id = t2.id
left join t3 on t1.id = t3.id  

我读到我可以使用DetachedCriteria,但是到目前为止我看到的例子只返回id,例如:

SELECT * from t1 where t1.id in (select subquery.id from subquery);

1 个答案:

答案 0 :(得分:0)

如果需要编写如下所示的子查询:

select * from A 
where (A.col1, A.col2) in (select B.col1, B.col2 from B);

使用Subqueries.propertiesIn的标准是可能的。

final ProjectionList subqueryProjections = Projections.projectionList();
subqueryProjections.add(Projections.property("col1"));
subqueryProjections.add(Projections.property("col2"));

DetachedCriteria subquery = DetachedCriteria.forClass(B.class);
subquery.setProjection(subqueryProjections);

mainCriteria.add(Subqueries.propertiesIn(new String[] {"col1", "col2"}, subquery));

这对于作为笛卡尔积的from a, b, c部分没有帮助。

注意:我从未在纯Java环境中使用它,只使用Grails with Hibernate 4.3。并且它不适用于所有数据库(H2不支持多个字段)。