Java/JPA with Error
[해결 방법] java.lang.IllegalArgumentException
HJ0216
2023. 9. 22. 17:35
👉 기본 환경
- 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
36
|
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);
// Scala Type Projection
em.createQuery("select distinct m.name, m.age from Member m", Order.class)
.getResultList();
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
}
}
|
🖨️오류
1
2
3
4
5
6
|
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [jpql.Order]
at org.hibernate.internal.AbstractSharedSessionContract.resultClassChecking(AbstractSharedSessionContract.java:870)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:817)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at jpql.Main.main(Main.java:54)
|
📡 원인
return type이 불일치
📰 해결 방법
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
36
|
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);
// Scala Type Projection
em.createQuery("select distinct m.name, m.age from Member m")
.getResultList();
tx.commit(); // transaction 종료 후 commit
} catch (Exception e) {
tx.rollback(); // 문제가 생길 경우, rollback 진행
e.printStackTrace();
} finally {
em.close(); // tx에 문제가 생기더라도 em 반드시 종료
}
emf.close();
}
}
|
return 타입 생략