import static com.example.inflearnquerydsl.entity.QMember.member;
@SpringBootTest
@Transactional
public class QuerydslBasicTest {
@PersistenceContext
EntityManager em;
JPAQueryFactory queryFactory; // 동시성 문제?
// 스프링 프레임워크는 여러 쓰레드에서 동시에 같은 EntityManager에 접근해도,
// 트랜잭션 마다 별도의 영속성 컨텍스트를 제공하기 때문에, 동시성 문제는 걱정하지 않아도 된다.
@BeforeEach
public void before() {
queryFactory = new JPAQueryFactory(em);
Team teamA = new Team("teamA");
Team teamB = new Team("teamB");
em.persist(teamA);
em.persist(teamB);
Member member1 = new Member("member1", 10, teamA);
Member member2 = new Member("member2", 20, teamA);
Member member3 = new Member("member3", 30, teamB);
Member member4 = new Member("member4", 40, teamB);
em.persist(member1);
em.persist(member2);
em.persist(member3);
em.persist(member4);
}
@Test
public void startJPQL() {
String qlString =
"select m from Member m " +
"where m.username = :username";
Member findMember = em.createQuery(qlString, Member.class)
.setParameter("username", "member1")
.getSingleResult();
assertThat(findMember.getUsername()).isEqualTo("member1");
}
@Test
public void startQuerydsl() {
Member findMember = queryFactory
.select(member)
.from(member)
.where(member.username.eq("member1")) //파라미터 바인딩 처리
.fetchOne();
assertThat(findMember.getUsername()).isEqualTo("member1");
}
}
em.find() // DB를 통해 실제 엔티티 객체 조회
em.getReference() // 가짜 엔티티(프록시) 객체 조회
Team team = new Team();
team.setName("teamA");
em.persist(team);
Member member = new Member();
member.setUsername("member1");
member.setTeam(team);
em.persist(member);
em.flush();
em.clear();
Member findMember = em.find(Member.class, member.getId());
Hibernate:
select
member0_.MEMBER_ID as MEMBER_I1_0_0_,
member0_.TEAM_ID as TEAM_ID3_0_0_,
member0_.USERNAME as USERNAME2_0_0_
from
Member member0_
where
member0_.MEMBER_ID=?
Hibernate:
select
member0_.MEMBER_ID as MEMBER_I1_0_0_,
member0_.TEAM_ID as TEAM_ID3_0_0_,
member0_.USERNAME as USERNAME2_0_0_,
team1_.TEAM_ID as TEAM_ID1_1_1_,
team1_.name as name2_1_1_
from
Member member0_
left outer join
Team team1_
on member0_.TEAM_ID=team1_.TEAM_ID
where
member0_.MEMBER_ID=?
참고
https://velog.io/@dbsrud11/JPA-Hibernate-SpringData-JPA-%EC%B0%A8%EC%9D%B4%EC%A0%90
https://doing7.tistory.com/123
https://ict-nroo.tistory.com/132
https://velog.io/@jin0849/JPA-%ED%94%84%EB%A1%9D%EC%8B%9CProxy