2014-07-11 195 views
1

我有一個MySQL查詢,我想將這個查詢轉換爲Hibernate查詢。這是我到目前爲止嘗試過的。將mysql查詢轉換爲hibernate查詢

userInQuery = "SELECT * FROM log where userName in("; 
userCountQuery = "SELECT count(*) FROM log where userName in("; 

for (int i = 0; i < users.length; i++) { 
    userInQuery += "'" + users[i] + "',"; 
    userCountQuery += "'" + users[i] + "',"; 
} 

userInQuery = userInQuery.substring(0, userInQuery.lastIndexOf(","))+ ") and 
    systemdate >= STR_TO_DATE('" + fromDt+ "' ,'%Y-%m-%d') and systemdate <= 
    STR_TO_DATE('"+ toDate + "','%Y-%m-%d')"; 

userCountQuery = userCountQuery.substring(0, userCountQuery.lastIndexOf(","))+ ") 
    and systemdate >= STR_TO_DATE('"+ fromDt+ "' ,'%Y-%m-%d') and systemdate <= 
    STR_TO_DATE('"+ toDate + "','%Y-%m-%d')"; 

//System.out.println("Final userInQuery : " + userInQuery); 

psmt = conn.prepareStatement(userInQuery); 

rscount = stmt.executeQuery(userCountQuery); 
+0

給你的MySQL查詢,以獲取有關什麼ü[R問清晰的概念。 – OO7

+0

@ user000324我想問如何在查詢和STR_TO_DATE在休眠 – user3441816

回答

1

使用Hibernate查詢:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY"); 
String fromDate = "11-07-2014"; 
Date fromDt = formatter.parse(fromDate); 
String toDate = "11-07-2014"; 
Date toDt = formatter.parse(toDate); 

String userInQuery = "from log where userName in (:userList) and systemdate between :fromDate and :toDate"; 
Query q = s.createQuery(userInQuery); 
q.setParameterList("usersList", users); 
q.setParameter("fromDate", fromDt); 
q.setParameter("toDate", toDt); 
q.list(); 

注:這裏:用戶列表,:FROM日期&:TODATE是查詢參數。

使用Hibernate標準:

List<?> users = //get data from either a query or criteria 
criteria.add(Restrictions.and(Restrictions.in("userList", users),Restrictions.between("dateField", new SimpleDateFormat("dd-MM-YYYY").parse(fromDate), new SimpleDateFormat("dd-MM-YYYY").parse(toDate))); 

OR 

criteria.add(Restrictions.in("userList", users)); 
criteria.add(Restrictions.ge("systemDate", fromDt)); 
criteria.add(Restrictions.lt("systemDate", toDt)); 
+0

謝謝reply.but我得到這個異常「13:38:57,282錯誤[STDERR] java.lang.IllegalArgumentException:非法模式字符'Y' 13: 38:57,285錯誤[STDERR] \t at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:752) 13:38:57,286錯誤[STDERR] \t at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:559)「 – user3441816

+0

如果你使用** jdk 1.6 **然後使用(小寫)** y ** [SimpleDateFormat - JDK1.6](http://docs.oracle.com/javase/6/docs/api/java/text/ SimpleDateFormat.html)。使用** JDK 1.7 **您可以使用上述格式[SimpleDateFormat - JDK1.7](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) – OO7

+0

Log其中userName在(:userList)和systemdate:fromDate和:toDate之間。 這個查詢返回null? – user3441816

0

創建一個與您的情況相同的用戶標識列表,並將該列表傳遞給下面的查詢。

類似下面

Select x FROM X x WHERE x.y in :yList