6

我想获取介于两个时间戳之间的记录。我想要这个使用休眠。我尝试使用以下查询进行操作,但没有得到任何输出

HQL = "From AddressInfo address where address.addressId = '"+newValues.get("pickupAddress").toString()+"' and address.updatedDateAndTime between date_format('" + DateUtility.getTimeOfBeforeOneMinute() + "', '%m/%d/%y %H:%i:%s') and date_format('"+DateUtility.getCurrentDate()+"','%m/%d/%y %H:%i:%s')";

这是从控制台形成的 SQL 查询:

select addressinf0_.T_ADM_NPK_ADDRESS_ID as T1_5_, addressinf0_.T_ADM_VNM_USER_ID as T2_5_, addressinf0_.T_ADM_FPK_USER_ASSIGNED_ID as T3_5_, addressinf0_.T_ADM_VNM_STREET_1 as T4_5_, addressinf0_.T_ADM_VNM_STREET_2 as T5_5_, addressinf0_.T_ADM_VNM_STREET_3 as T6_5_, addressinf0_.T_ADM_VNM_CITY as T7_5_, addressinf0_.T_ADM_VNM_STATE as T8_5_, addressinf0_.T_ADM_VNM_ZIPCODE as T9_5_, addressinf0_.T_ADM_DNM_LATITUDE as T10_5_, addressinf0_.T_ADM_DNM_LONGITUDE as T11_5_, addressinf0_.T_ADM_TNM_CREATE_DATETIME as T12_5_, addressinf0_.T_ADM_TNM_UPDATE_DATETIME as T13_5_ from t_address_master addressinf0_ where addressinf0_.T_ADM_NPK_ADDRESS_ID='19' and (addressinf0_.T_ADM_TNM_UPDATE_DATETIME between date_format('Tue Oct 02 17:09:53 EDT 2012', '%m/%d/%y %H:%i:%s') and date_format('Tue Oct 02 17:10:53 EDT 2012', '%m/%d/%y %H:%i:%s'))

我的数据库有一条记录 T_ADM_TNM_UPDATE_DATETIME = 10/2/2012 5:10:40 PM

但是结果集无法获取此查询...我不知道我哪里出错了。

谁能进一步指导我

4

2 回答 2

7

您应该使用 HQL 参数而不是连接。

举个例子:

Map<String, Object> parameterNameAndValues = new HashMap<String, Object>();

Date startDate;
Date endDate;

// Assign values to startDate and endDate

parameterNameAndValues.put("startDate", startDate);
parameterNameAndValues.put("endDate", endDate);

String hqlQuery = "FROM EntityName WHERE fechaInicio BETWEEN :startDate AND :endDate";

Query query = this.sessionFactory.getCurrentSession().createQuery(hqlQuery);

for (Entry<String, Object> e : parameterNameAndValues.entrySet()) {
    query.setParameter(e.getKey(), e.getValue());
}

return query.list();

这将绑定日期参数,hibernate 将为您进行必要的转换,以避免完整性检查和错误。请记住,即使 MySQL 以该格式保存 Date 对象,其他数据库也可能不会,它会破坏 Hibernate 的帮助。

于 2012-10-03T16:06:45.953 回答
-1

使用此代码:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

java.util.Date date = df.parse(startDate);

java.util.Date date1 = df.parse(endDate);

Date fromDate = new java.sql.Date(date.getTime()); 

Date toDate = new java.sql.Date(date1.getTime());

return this.sessionFactory.openSession().createQuery("From UserDailyLogin where userProfile.userId='"+id+"' And createdDate BETWEEN '"+startDate+ "' AND '"+endDate+"' ").list();   
于 2017-08-28T10:30:20.997 回答