Flavio
Flavio

Reputation: 915

How to enforce Hibernate to return only one entity instead of bunch?

Here is my problem. I'm searching a User entity in DB using Hibernate. But my search criteria allows not only one result (users). How to enforce Hibernate to return only single User object instead of bunch?

My code:

public User findUser(String name) {
    return (User) getSession().
            createCriteria(User.class).
            add(Restrictions.like("name", name, MatchMode.ANYWHERE)).
            uniqueResult();
}

Example of Hibernate exception when matching more than one result:

org.hibernate.NonUniqueResultException: query did not return a unique result: 5

Upvotes: 2

Views: 2738

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

Your query returns several users, and not just one. uniqueResult() is for queries returning only one user, and it throws an exception to make you realize that the query doesn't actually return a unique result. If you just want the first of the users returns by the query, use

Criteria c = getSession().
        createCriteria(User.class).
        add(Restrictions.like("name", name, MatchMode.ANYWHERE));
c.setMaxResults(1);
List<User> users = c.list();
return users.isEmpty() ? null : users.get(0);

Note that you can't have any guarantee about which of the 5 users will actually be returned. To be more deterministic, you should add an order by id clause to the query.

Upvotes: 4

Related Questions