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()
- 결과가 없을 경우, NoResultException 예외 발생
- 결과가 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()
'Java > JPA with Error' 카테고리의 다른 글
[해결방법] duplicateKeyException (0) | 2024.08.12 |
---|---|
[해결방법] JdbcTypeRecommendationException (0) | 2023.12.25 |
[해결방법] BeanCreationException (0) | 2023.12.25 |
[해결 방법] org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl ... is closed (1) | 2023.10.08 |
[해결 방법] org.hibernate.QueryException (0) | 2023.09.26 |