Java/JPA with Error

[해결방법] EmptyResultDataAccessException

HJ0216 2024. 8. 11. 20:50

EmptyResultDataAccessException

Environment
Language: Java
DB: MySQL

 

오류

Caused by: jakarta.persistence.NoResultException: No result found for query [select u from User u where u.email = :email]
	at org.hibernate.query.spi.AbstractSelectionQuery.getSingleResult(AbstractSelectionQuery.java:476)
	at com.msgs.user.repository.UserRepository.findByEmail(UserRepository.java:19)

 

 

원인

public Optional<User> findByEmail(String email) {
    User user = em.createQuery("select u from User u where u.email = :email", User.class)
            .setParameter("email", email)
            .getSingleResult();
    return Optional.ofNullable(user);
}

 

  • getSingleResult()
  1. 결과가 없을 경우, NoResultException 예외 발생
  2. 결과가 2개 이상일 경우, NonUniqueResultException 예외 발생

 

해결

public Optional<User> findByEmail(String email) {
    List<User> users = em.createQuery("select u from User u where u.email = :email", User.class)
            .setParameter("email", email)
            .getResultList();
    if (users.isEmpty()) {
        return Optional.empty();
    } else {
        return Optional.of(users.get(0));
    }
}

 

  • getSingleResult() → getResultList()