使用Criteria或DetachedCriteria Hibernate这个查询是否可行

问题很简单,可以使用Criteria或DetachedCriteria在Hibernate中完成此查询吗?我想不是,但我想做这个问题可能存在一个解决方法.

SELECT
  COLUMNS 
FROM table
WHERE id not in (
    SELECT * FROM (
        SELECT id 
        FROM table
        WHERE
        SOMECONDITIONS   
        ORDER BY timestamp desc limit 0, 15
  ) 
  as t);

我将@Dean Clark的答案标记为正确,但另一个问题出现如下

where can i find the findByCriteria from SessionFactory we are not using Spring 
最佳答案
要完全匹配您的查询,您确实需要执行2个步骤,但如果可能,我会避免这种情况:

final Criteria innerCriteria = getSession().createCriteria(YourEntity.class);
// SOME CONDITIONS
innerCriteria.add(Restrictions.eq("someColumn", "someValue"));
innerCriteria.addOrder(Order.desc("timestamp"));
innerCriteria.setMaxResults(15);
innerCriteria.setProjection(Projections.id());
List<YourIdClass> ids = innerCriteria.list();


final Criteria criteria = getSession().createCriteria(YourEntity.class);
criteria.add(Restrictions.not(Restrictions.in("id", ids)));
List<YourEntity> results = criteria.list();

您尝试识别的物体是否具有相同的“SOMECONDITIONS”?如果是这样,这将在功能上实现您正在寻找的:

final DetachedCriteria criteria = DetachedCriteria.forClass(YourEntity.class);
// SOME CONDITIONS
criteria.add(Restrictions.eq("someColumn", "someValue"));
criteria.addOrder(Order.desc("timestamp"));
getHibernateTemplate().findByCriteria(criteria, 16, 9999999);

转载注明原文:使用Criteria或DetachedCriteria Hibernate这个查询是否可行 - 代码日志