Hibernate - 使用date where子句过滤单列数据

时间:2017-09-17 12:55:20

标签: java mysql hibernate

让我们说一个表ABC有两列,即ID& CREATED_DATE

我想获取创建的ID,我们可以说'09-11-2017''09-17-2017'

在SQL查询下工作正常,但我想使用hibernate实现相同的逻辑。

select ID from ABC where between TO_DATE('09-11-2017', 'MM-DD-YYYY')  AND TO_DATE('09-17-2017', 'MM-DD-YYYY')

我的代码无效。

public List getData(final Date startDate, final Date endDate){

    String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
    SQLQuery query = getSession().createSQLQuery(sqlString);
    query.setParameter(CREATED_DATE);
    return query.list();
}

3 个答案:

答案 0 :(得分:3)

您缺少结束日期参数:

query.setParameter(CREATED_DATE, startDate);
query.setParameter(END_DATE, endDate);

答案 1 :(得分:2)

它不起作用,因为您没有设置正确的参数:

String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
SQLQuery query = getSession().createSQLQuery(sqlString);
query.setParameter("startDate ", start_date);
query.setParameter("endDate", end_date);
return query.list();

答案 2 :(得分:2)

参数必须与查询

上的字符串匹配

试试这个:

public List getData(final Date startDate, final Date endDate){

    String sqlString = "select ID from ABC where CREATED_DATE between :startDate and :endDate";
    SQLQuery query = getSession().createSQLQuery(sqlString);
    query.setParameter("startDate",startDate);
    query.setParameter("endDate",endDate);
    return query.list();
}

-

pscar13