如何比较HQL中的时间戳字段?

时间:2018-05-27 21:58:16

标签: mysql sql hibernate

我在表中有一个Java.Util.Timestamp列,我无法与WHERE子句中的变量进行比较。使用此代码:

        // Using Calendar to convert Java Date 'horarioEliminar' to Sql Timestamp 't'
        Calendar cal = Calendar.getInstance();
        cal.setTime(horarioEliminar);
        cal.set(Calendar.MILLISECOND, 0);

        Timestamp t = new java.sql.Timestamp(cal.getTimeInMillis());

        String horQ = "FROM Academia.Horarios WHERE horario ="+ t;
        horario = (Horarios) session.createQuery(horQ).uniqueResult();

我有一个例外:

  

ERROR [http-nio-8080-exec-873] org.hibernate.hql.internal.ast.ErrorCounter.reportError第1:57行:意外令牌:10

但我检查了System.out.println(t)结果是否与存储在horario列中的值匹配。如何正确比较这两个时间戳?

1 个答案:

答案 0 :(得分:0)

尝试将时间戳设置为查询参数,如下所示:

 Timestamp t = new java.sql.Timestamp(cal.getTimeInMillis());

 String horQ = "FROM Academia.Horarios WHERE horario = :ts";
 horario = (Horarios) session.createQuery(horQ).setParameter("ts", t).uniqueResult();