将mysql查询转换为hibernate查询

时间:2014-07-11 03:53:15

标签: java mysql hibernate

我有一个MySQL查询,我想将此查询转换为Hibernate Query。这是我到目前为止所尝试过的。

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

2 个答案:

答案 0 :(得分: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();

注意:此处:userList,:fromDate&amp; :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));

答案 1 :(得分:0)

根据您的情况创建用户ID列表,并将该列表传递给以下查询。

如下所示

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