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);