将正常的sql查询转换为Criteria查询

时间:2013-07-23 13:41:43

标签: hibernate criteria

我有一个正常的SQL查询,如:

  String sql = "select * from Comm c where " +
        "c.id in (select max(c.id) from Comm c, ReadComm rc where c.createdby=1 or (c.createdby = 1 and rc.userid=5) and c.id=rc.commid group by c.commThread) " +
        "and c.isdelete = false order by c.senton desc";

是否可以将此类查询转换为条件?我搜索了它,但没有得到这样的例子。

谢谢。

1 个答案:

答案 0 :(得分:0)

是的,请查看DetachedCriteria和Subqueries

这样的事情:

// Create subquery
DetachedCriteria sub = DetachedCriteria.forClass(Comm.class, "sub");
sub.createAlias("sub.readComm", "rc");
sub.add(Restrictions.or(Restrictions.eq("sub.createdby", 1), ...
sub.setProjection(Projections.max("sub.id"));

// Create main query
Criteria.forClass(Comm.class)
   .add(Subqueries.propertyEq("id", sub)) // id property == value of subquery
   .add(Restrictions.eq("isdelete", false))
   .addOrder(Order.desc("senton"))
   .list();