我有两张桌子:
A (x, y, z, date1, date2)
B (t, date1, date2)
我想执行这样的查询:
SELECT A.x, A.y, A.z, A.date1
FROM A, B
WHERE A.date1 < B.date1
AND (A.date2 is null or A.date2 <= B.date2 )
ORDER BY A.x DESC;
如何使用Hibernate Criteria执行此操作?
答案 0 :(得分:1)
String dateIdValue = "...";
Class<?> mainClass = A.class;
Class<?> dateClass = B.class;
String colDate1 = "date1";
String colDate2 = "date2";
String colDateId = "id";
Property date1Prop = Property.forName(colDate1);
Property date2Prop = Property.forName(colDate2);
DetachedCriteria date1Criteria = DetachedCriteria.forClass(dateClass)
.setProjection(date1Prop)
.add(Restrictions.eq(colDateId, dateIdValue));
DetachedCriteria date2Criteria = DetachedCriteria.forClass(dateClass)
.setProjection(date2Prop)
.add(Restrictions.eq(colDateId, dateIdValue));
Criteria criteria = getSession().createCriteria(mainClass)
.add(date1Prop.lt(date1Criteria))
.add(Restrictions.or(date2Prop.isNull(), date2Prop.le(date2Criteria)))
.addOrder(Order.desc("x"));
/*
SELECT A.*
FROM A, P
WHERE A.date1 < P.date1
AND (A.date2 is null or A.date2 <= P.date2 )
ORDER BY A.x DESC;
*/
答案 1 :(得分:0)
使用子查询。这样的事情。
select a,b,c,date3
from A
where date3 is null or
date3 < (select p.date1 from P p)
order by a desc;
无论其!如果你没有实体之间的映射关系,那么这不是Hibernate的设计目标,最好是直接使用SQL。