早上好,

我正在尝试以下事情:

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

 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为null ...我没有错误或异常,这是操作日志。

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中运行相同的查询,则可以使用...

我做错了什么?谢谢

最佳答案

您似乎没有将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);行。

10-01 05:01