2016-02-12 18 views
0

我在使用限制時遇到問題。我有一個表employee已結構如下:如何使用裏面包含OR條件的AND SqlRestriction?

id : int (primary key) 
create_date : datetime 
modified_date: datetime 

我用下面的代碼列出下來一名僱員,如果它的創建/一個特定的時間間隔內修改:

Criteria criteria = getSession().createCriteria(Employee.class); 

criteria.add(Restrictions.eq("id", employeeId)); 

if (interval > 0) { 
    String sql = "{alias}.create_date > DATE_SUB(NOW(), INTERVAL " + interval + " SECOND) OR {alias}.modified_date > DATE_SUB(NOW(), INTERVAL " + interval + " SECOND)"; 
    criteria.add(Restrictions.sqlRestriction(sqlWhere)); 
} 

List<Employee> employeeList = criteria.list(); 

請注意, SqlRestriction內有一個OR條件。

現在假設employeeId = 10interval = 3600employeeList包含其他員工以及id = 10,這不應該發生。

我應該用Restrictions.andRestrictions.conjunction來解決嗎?或者我錯過了別的東西?

+0

試試這個。 http://stackoverflow.com/questions/57484/how-do-you-or-criteria-together-when-using-a-criteria-query-with-hibernate –

+0

@ user4246662:我在發佈之前已經經歷過。我看到這是關於OR'ing的限制! – blackSmith

回答

1

這裏沒有魔法。使用限制和方法將兩個標準分組。 Hibernate應該自動將子查詢分組以達到預期的結果。

Criteria criteria = getSession().createCriteria(Employee.class); 

Criterion whereClause = Restrictions.eq("id", employeeId); 
if (interval > 0) { 
    String sql = "{alias}.create_date > DATE_SUB(NOW(), INTERVAL " + interval + " SECOND) OR {alias}.modified_date > DATE_SUB(NOW(), INTERVAL " + interval + " SECOND)"; 
    Criterion andConjunction = Restrictions.and(
     whereClause, 
     Restrictions.sqlRestriction(sqlWhere) 
    ); 

    whereClause = andConjunction; 
} 
criteria.add(whereClause); 

List<Employee> employeeList = criteria.list(); 
+0

感謝您的快速回答。我正在測試'Restrictions.conjunction',它也給出了預期的結果。這兩者有什麼區別嗎? – blackSmith

+1

@blackSmith Restrictions.conjunction返回在某種意義上應該被視爲由AND連接的標準列表,允許您有兩個以上。並不是說你不能用Restrictions.and來做同樣的事情,但是你必須把它稱爲n-1次,其中n是條件的數量。總而言之,不,它的工作原理是一樣的。如果你有很多條件用AND或OR連接(析取),它只是使寫出更方便。 – Neil