Java/JPA with Error
[해결 방법] javax.persistence.NoResultException
HJ0216
2023. 9. 22. 17:01
👉 기본 환경
- Language: Java
- DB: H2 Database
- IDE: IntelliJ
⌨️ 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin(); // transaction 시작 선언
try {
Member member1 = new Member();
member1.setName("Member1");
em.persist(member1);
Member member2 = new Member();
member2.setName("Member1");
em.persist(member2);
TypedQuery<Member> query = em.createQuery("select m from Member m where m.name='Member2'", Member.class);
Member findMember = query.getSingleResult();
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
}
}
|
🖨️오류
1
2
3
4
|
javax.persistence.NoResultException: No entity found for query
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1583)
at jpql.Main.main(Main.java:29)
|
📡 원인
getSingleResult()의 result가 0개
📰 해결 방법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin(); // transaction 시작 선언
try {
Member member1 = new Member();
member1.setName("Member1");
em.persist(member1);
Member member2 = new Member();
member2.setName("Member1");
em.persist(member2);
TypedQuery<Member> query = em.createQuery("select m from Member m where m.name='Member2'", Member.class);
List<Member> resultList = query.getResultList();
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
}
}
|
Exception 방지를 위해 getResultList() 사용
→ 결과가 0개일 때, 빈 객체 반환