반응형
JPA 게시글은 대부분 인프런의 김영한님의 강의인 '자바 ORM 표준 JPA 프로그래밍' 기반으로 내용을 정리했습니다.
엔티티 직접 사용
기본 키 값
- JPQL에서 엔티티를 직접 사용하면 SQL에서 해당 엔티티의 기본 키 값을 사용
- 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 query = "select m From Member m where m = :member";
Member findMember = em.createQuery(query, Member.class)
.setParameter("member", member)
.getSingleResult();
- 식별자를 직접 전달
String query = "select m From Member m where m.id = :memberId";
Member findMember = em.createQuery(query, Member.class)
.setParameter("memberId", member.getId())
.getSingleResult();
- 실행된 SQL
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=?
외래 키 값
String query = "select m From Member m where m.team = :team"; // m.team이 DB 입장에서는 외래키
List<Member> findMember = em.createQuery(query, Member.class)
.setParameter("team", teamA)
.getResultList();
for (Member mem : findMember) {
System.out.println("mem = " + mem);
}
Hibernate:
/* select
m
From
Member m
where
m.team = :team */ 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_.TEAM_ID=?
mem = Member{id=3, username='회원1', age=0}
mem = Member{id=4, username='회원2', age=0}
반응형