Search code examples
javaspring-mvchql

How to return int from query?


I have this method in my dao implementation, and im trying to return int from the query and put it in the roomNumber int variable, but im not sure if it`s the right syntax... and probably there are other errors. In debug mode i see that the int roomNumber field doesnt get any value, its value is 0 when i step over it.

@Override
    public int getRoomNumber(int bookingId) {
        Session session = sessionFactory.getCurrentSession();

        Query query = session.createQuery("select room.roomId from Booking where bookingId=:bookingId");

        query.setParameter("bookingId", bookingId);

        int roomNumber = query.getFirstResult();

        return roomNumber;
    }

Booking table in db:

enter image description here

for the query i have tried also this:

select room_room_id from Booking where bookingId=:bookingId

Solution

  • For these purposes there is method uniqueResult():

    int roomNumber = ((Number)query.uniqueResult()).intValue();
    

    EDIT: if you use hibernate version > 5.2.2 you possibly will want change this to method getSingleResult():

    Hibernate UniqueResult Deprecated