gpt4 book ai didi

java - 将 mysql 查询转换为 hibernate 查询

转载 作者:行者123 更新时间:2023-11-29 00:11:52 26 4
gpt4 key购买 nike

我有一个 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);

最佳答案

使用 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 & :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));

关于java - 将 mysql 查询转换为 hibernate 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com