2016-12-30 44 views
0

這種方法:注入一個子查詢到標準查詢

public List<User> exampleForSO(int size, int page, boolean name, boolean email) { 

     Criteria criteria = getSession().getCurrentSession().createCriteria(User.class); 

     if (name) { 
      criteria.add(Restrictions.isNotEmpty("name")); 
     } 

     if (email) { 
      criteria.add(Restrictions.isNotEmpty("email")); 
     } 

     criteria.setMaxResults(size); 
     criteria.setFirstResult(page); 

     List<User> users = criteria.list(); 

     return users; 
    } 

產生如下SQL:

Hibernate: select this_.name as y0_, this_.id as y1_ from users this_ where this_.id is not null limit ? offset ? 

我怎麼能做到這一點查詢?

Hibernate: select this_.name as y0_, this_.id as y1_, COUNT(*) OVER() as overallCount from users this_ where this_.id is not null limit ? offset ? 

基本上我想這個小行添加到查詢:

COUNT(*) OVER() as overallCount 

有什麼建議?

這可以用DetachedCriteria解決嗎?

我曾嘗試:

  1. 創建的DetachedCriteria並將其添加爲一個子查詢到實際的標準查詢,這是不是一種選擇,我不想要一個子查詢。

  2. 生成RawSQL字符串並嘗試將其注入查詢中,但未成功。

回答

0

以防萬一有人試圖達到相同。

這是我做的:

我在User類創建一個領域,像這樣:

@Formula("COUNT(*) OVER()") 
private Long overallCount; 

你可以閱讀更多關於Hibernate Formula Annotation here