我正在尝试使用Criteria构建一个复杂的查询。 我在SQL中创建了查询,以便向您解释我想要的内容:
SELECT ID, DATE
FROM SELLS v
WHERE DATE > (SELECT min(DATE)
FROM SELLS
WHERE CODE IN (12345, 12344)
AND ID = v.ID)
AND DATE>TO_DATE('2015-01-01', 'YYYY-MM-DD')
AND DATE<TO_DATE('2016-01-01', 'YYYY-MM-DD')
GROUP BY ID, DATE
这是我的班级:
@Entity
@Table(name = "SELLS")
@Getter
public class Sells {
@Id
@Column(name = "SELL_ID")
private Integer idSell;
@Column(name = "ID")
private Integer id;
@Column(name = "DATE")
private Date date;
@Column(name = "CODE")
private String code;
}
我在Criteria中尝试的内容(开始和结束是WHERE中的两个日期('2015-01-01'和'2016-01-01'):
Criteria c = getSession().createCriteria(Sells.class);
List subquery = getSession().createCriteria(Sells.class)
.add(Restrictions.in("code", {"12345", "12344"}))
.createAlias("Sells.id", "id")
.setProjection(Projections.projectionList()
.add(Projections.min("date")))
.list();
c.add(Restrictions.ge("date", subquery));
c.add(Restrictions.ge("date", start));
c.add(Restrictions.le("date", end));
c.setProjection(Projections.projectionList()
.add(Projections.groupProperty("date"))
.add(Projections.groupProperty("id")));
我也尝试使用DetachedCriteria但失败了。
DetachedCriteria query = DetachedCriteria.forClass(Sells.class, "v");
DetachedCriteria subquery = DetachedCriteria.forClass(Sells.class, "bv")
.add(Restrictions.in("bv.code", codes))
.add(Restrictions.eq("bv.id", "v.id")
.setProjection(Projections.projectionList()
.add(Projections.min("bv.date")));
query.add(Restrictions.ge("v.date", subquery))
.add(Restrictions.ge("v.date", start))
.add(Restrictions.le("v.date", end))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("v.date"))
.add(Projections.groupProperty("v.id")));
如果有人知道如何做到这一点会对我有所帮助!
编辑:这看起来更好但仍无效:
Criteria query = getSession().createCriteria(Sells.class, "v");
DetachedCriteria subquery = DetachedCriteria.forClass(Sells.class, "bv")
.add(Restrictions.in("bv.code", codes))
.add(Restrictions.eq("bv.id", "v.id")
.setProjection(Projections.projectionList()
.add(Projections.min("bv.date")));
query.add(Restrictions.ge("v.date", subquery))
.add(Restrictions.ge("v.date", start))
.add(Restrictions.le("v.date", end))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("v.date"))
.add(Projections.groupProperty("v.id")));
org.hibernate.criterion.DetachedCriteria无法强制转换为java.util.Date