tags:

views:

258

answers:

1

Hi,

i am experimenting using Hibernate.

I am trying to get a User by id this is what i do

public User get(DetachedCriteria dc){
    List<User> users = getHibernateTemplate().findByCriteria(dc);
    if(users != null)
    {
        return users.get(0);
    }
    else return null;
}

but it fails when the user is not in the database. Could you help me to understand how to achieve this?

Thanks

+2  A: 

If you want to load something by ID you should really be using either Load or Get. Ayende has a good post on the difference between The difference between Get, Load and querying by id.

As far as why your query is failing when the user isn't in the database. It's because the query will return an empty list, which is different from null. So when you try to access the 0th element of a list that has nothing in it, you're probably getting an index out of bounds exception.

R0MANARMY