👉 기본 환경
- 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개일 때, 빈 객체 반환
'Java > JPA with Error' 카테고리의 다른 글
[해결 방법] java.lang.IllegalArgumentException (0) | 2023.09.22 |
---|---|
[해결 방법] javax.persistence.NonUniqueResultException (0) | 2023.09.22 |
[해결 방법] org.h2.jdbc.JdbcSQLSyntaxErrorException (0) | 2023.09.22 |
[해결 방법] org.hibernate.QueryException (0) | 2023.09.20 |
[해결 방법] org.hibernate.exception.ConstraintViolationException (0) | 2023.09.19 |