Question

I have a problem because I am tryting to access an empty object, don't know how to solve it, without hibernate would be checking the ResulSet object.next is not 0, but here with Hibernate, I am trying to do this without success:

public User buscaHotel(int id){

    User user =null;
    SessionFactory sf = open();
    Session ss=sf.openSession();
    ss.beginTransaction();      
    Query query = ss.createQuery("from User_table where userId = :id ");
    query.setParameter("id", id);
    List<?> list = query.list();
    if (list != null){
        System.out.println("Not NULL");
    user = (User)list.get(0);
    ss.getTransaction().commit();
    ss.close();
    return user;
    }
    else {
    ss.getTransaction().commit();
    ss.close();
    return user;
    }
}

When I send an id that is not in the table, I got the error Array index out of bounds, because it enters in the if (list !=null). I appreciate any help, thank you very much.

Était-ce utile?

La solution

Quick fix for your code

You need to check if the list is empty before getting its first element.

Change this line:

user = (User)list.get(0);

To this:

if(list.size() > 0) user = (User)list.get(0);

Better solutions

You can use Query#uniqueResult() when you expect there to only be one record/entity returned. Then you don't have to worry about handling a list, like this:

User user = (User) query.uniqueResult();

Note that uniqueResult() will throw an exception if there is actually more than one record returned.

However, the typical way to fetch a single entity by id is to use Session#get(Class, Serializable) (returns null if not found) or Session#load(Class, Serializable) (throws exception if not found). That way, you don't have to write the query at all. Like this:

User user = (User) session.get(User.class, id);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top