Hibernate uniqueResult为null,但它不应该

时间:2015-12-15 09:32:39

标签: java hibernate

早上好,

我正在尝试以下事情:

在更新对象之前,我想从最后一条记录中检索一个字段,将其添加到新行中。所以这就是我做的事情

 int idLuce = Integer.parseInt(msg);
 Illuminazione illuminazione = new Illuminazione();
 session.beginTransaction();
 selectQuery = "SELECT dateTime from Illuminazione i where i.idLuce = :idLuce ORDER BY i.dateTime ASC";
 theQuery = session.createQuery(selectQuery).setProperties(illuminazione).setFirstResult(0)
.setMaxResults(1);
 lastDate = (Date) theQuery.uniqueResult();
 logger.debug("last date time is: "+lastDate);
 illuminazione.setLastDateTime(lastDate);
 illuminazione.setIdLuce(idLuce);
 illuminazione.setIsLit(true);
 Date date = new Date();
 illuminazione.setDateTime(new Timestamp(date.getTime()));
 session.save(illuminazione);
 session.getTransaction().commit();

一切都按预期工作,但是lastDate为空...我没有错误或异常,这是操作的日志..

2015-12-15 10:30:01.157 DEBUG [Thread-2]: HQL: SELECT dateTime from it.besmart.models.Illuminazione i where i.idLuce = :idLuce ORDER BY i.dateTime ASC
2015-12-15 10:30:01.159 DEBUG [Thread-2]: SQL: select illuminazi0_.date_time as col_0_0_ from SMARTPARK.illuminazione illuminazi0_ where illuminazi0_.id_luce=? order by illuminazi0_.date_time ASC
2015-12-15 10:30:01.161 DEBUG [Thread-2]: throwQueryException() : no errors

Hibernate: 
    select
        illuminazi0_.date_time as col_0_0_ 
    from
        SMARTPARK.illuminazione illuminazi0_ 
    where
        illuminazi0_.id_luce=? 
    order by
        illuminazi0_.date_time ASC limit ?
2015-12-15 10:30:01.187 DEBUG [Thread-2]: last date time is: null

2015-12-15 10:30:01.285 DEBUG [Thread-2]: Executing identity-insert immediately
2015-12-15 10:30:01.314 DEBUG [Thread-2]: 
    insert 
    into
        SMARTPARK.illuminazione
        (date_time, id_luce, isLit, last_date_time) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        SMARTPARK.illuminazione
        (date_time, id_luce, isLit, last_date_time) 
    values
        (?, ?, ?, ?)

显然,如果我在SQL中运行相同的查询,它可以工作......

我做错了什么?感谢

1 个答案:

答案 0 :(得分:1)

您似乎没有将idLuce传递给查询。试试这个

int idLuce = Integer.parseInt(msg);
session.beginTransaction();
selectQuery = "SELECT dateTime from Illuminazione i where i.idLuce = :idLuce ORDER BY i.dateTime ASC";
theQuery =  session.createQuery(selectQuery).setParameter("idLuce", idLuce).setMaxResults(1);
lastDate = (Date) theQuery.uniqueResult();

或者,在执行查询之前移动illuminazione.setIdLuce(idLuce);行。