在这个hibernate查询中比较日期的最合适的方法是什么?

时间:2014-05-27 14:39:45

标签: spring oracle hibernate spring-mvc hql

我有一个Spring MVC REST服务,它接受两个名为@RequestParamfrom的{​​{1}}。它们被解析为to并传递给我的DAO类中的以下方法。

java.util.Date

这会引发以下SQL错误:

@Override public List<ErrorsDTOEntity> getAllErrors(Date from, Date to) { try { Query query = getSession().createQuery( "SELECT NEW com.mydomain.esb.jpa.dto.ErrorsDTOEntity(ee, ec.message) " + "FROM ErrorsEntity ee, EventCodeEntity ec " + "WHERE ee.responseTime > " + from.getTime() + " " + "AND ee.responseTime < " + to.getTime() + " " + "AND ee.serviceResponseCode = ec.code " + "GROUP BY ee.domainName, ee.serviceName, ec.message, ee.serviceErrorCount, ee.errorTimestamp, " + "ee.deviceName, ee.servErrId, ee.serviceResponseCode, ee.elapsedTime, ee.forwardTime, " + "ee.responseCompletionTime, ee.responseSizeAverage, ee.requestSizeAverage, ee.responseTime " + "ORDER BY ee.domainName, ee.serviceName, ec.message, ee.errorTimestamp"); @SuppressWarnings("unchecked") List<ErrorsDTOEntity> services = (List<ErrorsDTOEntity>) query.list(); return services; } catch (HibernateException hex) { hex.printStackTrace(); } return null; }

构建此查询的正确方法是什么,因此我只能在org.hibernate.exception.SQLGrammarException: ORA-00932: inconsistent datatypes: expected TIMESTAMP got NUMBERfrom日期之间获取结果?

1 个答案:

答案 0 :(得分:0)

我想通了,这有效:

@Override
public List<ErrorsDTOEntity> getAllErrors(Date from, Date to) {
    try {
        Query query = getSession().createQuery(
                "SELECT NEW com.mydomain.esb.jpa.dto.ErrorsDTOEntity(ee, ec.message) "
                + "FROM ErrorsEntity ee, EventCodeEntity ec "
                + "WHERE ee.responseTime > :from "
                + "AND ee.responseTime < :to "
                + "AND ee.serviceResponseCode = ec.code "
                + "GROUP BY ee.domainName, ee.serviceName, ec.message, ee.serviceErrorCount, ee.errorTimestamp, "
                + "ee.deviceName, ee.servErrId, ee.serviceResponseCode, ee.elapsedTime, ee.forwardTime, "
                + "ee.responseCompletionTime, ee.responseSizeAverage, ee.requestSizeAverage, ee.responseTime "
                + "ORDER BY ee.domainName, ee.serviceName, ec.message, ee.errorTimestamp");
        query.setTimestamp("from", from);
        query.setTimestamp("to", to);

        @SuppressWarnings("unchecked")
        List<ErrorsDTOEntity> services = (List<ErrorsDTOEntity>) query.list();
        return services;

    } catch (HibernateException hex) {
        hex.printStackTrace();
    }       
    return null;
}