Reputation: 3228
Good morning,
I'm trying to the the following thing:
Before updating an object, i want to retrieve a field from the last record to add it in the new row. So this is what i did
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();
everything works as I expected, BUT lastDate is null... I get no errors or exceptions, this is the log of the operation..
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
(?, ?, ?, ?)
Obviously if I run the same query in SQL, it works...
What I'm doing wrong? Thanks
Upvotes: 2
Views: 2825
Reputation: 24423
You seem to not pass idLuce
into the query. Try this
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();
Or, move the illuminazione.setIdLuce(idLuce);
line before executing the query.
Upvotes: 1