Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[JPQL] 엔티티 직접 사용 본문

인프런/[인프런] 자바ORM 표준 JPA 프로그래밍

[JPQL] 엔티티 직접 사용

Seung__ 2021. 8. 16. 21:28

1. 엔티티 직접 사용 - 기본 키 값


  • JPQL에서 엔티티를 직접 사용하면 SQL에서 해당 엔티티의 기본 키 값을 사용함!
  • 엔티티는 DB에서 구분되는 기준이 기본 키임. 따라서 엔티티를 넘겨도 PK를 사용함.
  • JPQL
    • select count(m.id) from Member m //엔티티의 아이디를 사용
      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();
    •  
    • Hibernate: /* select m from Member m where m = :memberId */ select member0_.id as id1_0_, member0_.age as age2_0_, member0_.TEAM_ID as team_id5_0_, member0_.type as type3_0_, member0_.username as username4_0_ from Member member0_ where member0_.id=?
  • 식별자를 전달하는 경우
    • String jpql = “select m from Member m where m.id = :memberId”; 
      List resultList = em.createQuery(jpql) 
       .setParameter("memberId", memberId) 
       .getResultList();
    • Hibernate: 
          /* select
              m 
          from
              Member m 
          where
              m.id = :memberId */ select
                  member0_.id as id1_0_,
                  member0_.age as age2_0_,
                  member0_.TEAM_ID as team_id5_0_,
                  member0_.type as type3_0_,
                  member0_.username as username4_0_ 
              from
                  Member member0_ 
              where
                  member0_.id=?
  • 실행된 SQL
    • select m.* from Member m where m.id=?

 

 

 

2. 엔티티 직접 사용 - 외래 키 값.


  • 엔티티로 넘기는 경우
Team team = em.find(Team.class, 1L); 
String qlString = “select m from Member m where m.team = :team”; 
List resultList = em.createQuery(qlString) 
 .setParameter("team", team) 
 .getResultList();

  • 식별자(FK) 로 넘기는 경우
String qlString = “select m from Member m where m.team.id = :teamId”; 
List resultList = em.createQuery(qlString) 
 .setParameter("teamId", teamId) 
 .getResultList();
  • 실행된 SQL : FK사용함(연관된 FK 사용)
select m.* from Member m where m.team_id=?

'인프런 > [인프런] 자바ORM 표준 JPA 프로그래밍' 카테고리의 다른 글

[JPQL] 벌크 연산  (0) 2021.08.16
JPQL Named 쿼리  (0) 2021.08.16
다형성 쿼리  (0) 2021.08.16
Fetch Join2  (0) 2021.08.16
FETCH JOIN  (0) 2021.08.16
Comments