본문 바로가기
자바/JPA

[JPA/Java] JPQL 엔티티 직접 사용

by drCode 2023. 5. 11.
728x90
반응형

JPQL에서 엔티티를 직접 사용하면 SQL에서 해당 엔티티의 기본 키 값을 사용한다.

 

[JPQL]

jpql = "SELECT count(m.id) FROM Member m"; // 엔티티의 아이디를 사용

jpql = "SELECT count(m) FROM Member m"; // 엔티티를 직접 사용

 

[SQL] (위의 JPQL 둘다 같은 SQL을 실행)

SELECT count(m.id) as cnt FROM Member m

 

엔티티를 파라미터로 전달 시

String jpql = "select m from Member m where m = :member"; 
List resultList = em.createQuery(jpql) 
 .setParameter("member", member) 
 .getResultList();

 

식별자를 직접 전달 시

jpql = "select m from Member m where m.id = :id";
Member findMember = em.createQuery(jpql, Member.class)
        .setParameter("id", member.getId())
        .getSingleResult();

System.out.println("findMember = " + findMember);

 

실행된 SQL

SELECT m.* FROM Member m WHERE m.id=?

 

외래 키 값을 사용할 때(엔티티)

 

String qlString = "select m from Member m where m.team = :team";
List<Member> members = em.createQuery(qlString)
        .setParameter("team", teamA)
        .getResultList();

for (Member m : members) {
    System.out.println("m = " + m);
}
String qlString = "select m from Member m where m.team.id = :teamId";
List<Member> members = em.createQuery(qlString)
        .setParameter("teamId", teamA.getId())
        .getResultList();

for (Member m : members) {
    System.out.println("m = " + m);
}

 

실행된 쿼리

 

728x90
반응형

댓글