JPA/JPQL
JPQL 엔티티 조회
CodeMania
2021. 10. 15. 00:15
github 전체코드 주소(branch: jpql/entity)
JPQL에서는 PK(식별자)가 아닌 엔티티 자체를 사용해 데이터를 조회할 수 있다.
JPQL에서 엔티티를 직접 사용하면 SQL에서는 해당 Table의 PK 값을 사용한다.
음~~~ 별 거 아니니까 바로 살펴보도록 하겠다.
#JPQL: 엔티티를 직접 사용
select count(s) from Student s
#SQL: 엔티티의 PK를 사용
select count(s.id) as cnt from Student s
연관 엔티티를 그대로 사용하면 어떻게 될까?
JpaMain.java - 조회로직
String query = "select s from Student s where s.club = :club";
List<Student> students = em.createQuery(query, Student.class)
.setParameter("club", c1)
.getResultList();
for (Student s : students) System.out.println("s.name = " + s.getName());
Student Entity의 연관 Entity인 club을 조회했다.
로그를 살펴보면 FK를 통해 조회하는 것을 알 수 있다.
실행 후 로그
Hibernate: select student.* from Student student where student.CLUB_ID=?
s.name = code-mania
s.name = code-mania2
s.name = code-mania3
#JPQL
select s from Student s where s.id = :studentId
내가 평소에 주로 작성하던 JPQL은 위와 같다.
하지만 앞으로는 Entity를 직접 사용하여 조회하는 JPQL을 애용하도록 해야겠다.