Exception: javax.persistence.NonUniqueResultException: query did not return a unique result

Exception: javax.persistence.NonUniqueResultException: query did not return a unique result

The error message seems to be related to a database query executed within a Java application using the Java Persistence API (JPA).The error message indicates that a query executed against the database did not return a single unique result as expected instead, it returned multiple results. This error usually occurs when you use a query method that expects a single result, but the query actually returns multiple results. To resolve this issue, you might need to review your query logic to ensure that it only returns a single result when necessary. If the query is intentionally designed to return multiple results, you should use List () instead, which can handle multiple results. Additionally, you may need to refine your query criteria to ensure it returns a unique result when needed. Let’s understand with an example:
Let’s say you have an entity called User and you want to retrieve a user by their username using JPA. In this example, the findByUsername() method expects to find exactly one user with the given username. However, if there are multiple users with the same username in the database, this method will throw a NonUniqueResultException.

public class UserRepo {

    @PersistenceContext
    private EntityManager entityManager;

    public User findByUsername(String username) {
        return entityManager.createQuery("SELECT e FROM User e WHERE e.username = :username", User.class)
            .setParameter("username", username)
            .getSingleResult();
    }
}

To handle this kind of condition, you can modify the method to return a list of users. Now, if there are multiple users with the same username, the method will return all of them in a list.

public class UserRepo {

    @PersistenceContext
    private EntityManager entityManager;

    public List<User> findByUsername(String username) {
        return entityManager.createQuery("SELECT e FROM User e WHERE e.username = :username", User.class)
            .setParameter("username", username)
            .getResultList();
    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *