2013-07-23 62 views
0

我有一個正常的SQL查詢,如:翻譯普通的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"; 

是否有可能這樣的查詢轉換爲標準?我搜索了一下,但沒有得到這樣的例子。

謝謝。

+0

如果您正在使用Hibernate 4+那麼它很簡單,你可以使用'DetachedCriteria'和它們各自的預測(爲最大,組和ORDER BY)。 – Ziul

回答

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();