Video in progress
When does getSingleResult() throw an exception, and how do you write a query that may return no result?
If nothing is found it throws NoResultException, and if more than one row comes back it throws NonUniqueResultException. For a query that may be empty, use getResultStream().findFirst(), or in Spring Data a method that returns Optional.
📖 Answer
Simple code that leads to the error:
User u = em.createQuery("select u from User u where u.email = :e", User.class)
.setParameter("e", email)
.getSingleResult(); // if the email isn't found: NoResultException
By the JPA specification, these two exceptions specifically do not mark the transaction rollback-only, so you can catch them and carry on. But "not found" is an ordinary business case, and handling it through exceptions clutters the code. Also, if the error propagates out of a @Transactional method through the Spring proxy, the outer transaction ends up rollback-only, and you get UnexpectedRollbackException at commit.
The safe version:
Optional<User> u = em.createQuery("select u from User u where u.email = :e", User.class)
.setParameter("e", email)
.getResultStream()
.findFirst();
In Spring Data:
Optional<User> findByEmail(String email);
If nothing is found, an empty Optional comes back. If two rows are found, IncorrectResultSizeDataAccessException is still thrown, and that's a good thing: it means the email isn't unique in the database, which is a real problem.
Hibernate's uniqueResult() method returns null when there is no result; Hibernate 6 also has uniqueResultOptional(). And don't forget to put a UNIQUE index on the unique column (email) in the database, since an application-level check isn't enough.
Sign up to mark studied questions and save your progress.