Reputation: 89
I have a MySQL query, and I want to convert this query in to Hibernate Query. This is what I've tried so far.
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);
Upvotes: 1
Views: 1343
Reputation: 2807
Using Hibernate Query :
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();
Note : Here :userList, :fromDate & :toDate are query parameters.
Using Hibernate Criteria :
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));
Upvotes: 1
Reputation: 26067
Create a list of user id's as in your case, and pass that list to below query.
Something like below
Select x FROM X x WHERE x.y in :yList
Upvotes: 0