Skip to content

Commit

Permalink
[Week10][Chap3] Feat : 시작-JPQL vs Querydsl(#111)
Browse files Browse the repository at this point in the history
  • Loading branch information
songhee1 committed Nov 24, 2023
1 parent dace9d1 commit 0857223
Showing 1 changed file with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package study.querydsl.entity;

import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import static org.assertj.core.api.Assertions.*;

@SpringBootTest
@Transactional
public class QuerydslBasicTest {

@Autowired
EntityManager em;

JPAQueryFactory queryFactory;

@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";
//member1을 찾아라.
Member findMember = em.createQuery(qlString, Member.class)
.setParameter("username", "member1")
.getSingleResult();

assertThat(findMember.getUsername()).isEqualTo("member1");
}

@Test
public void startQuerydsl(){
QMember m = new QMember("m");
//variable은 식별용

Member findMember = queryFactory.select(m)
.from(m)
.where(m.username.eq("member1")) //파라미터 바인딩
.fetchOne();
/*querydsl 이점 : 1. 컴파일 시점에서 오류를 발견 2. 파라미터 바인딩을 자동으로 실행*/

assertThat(findMember.getUsername()).isEqualTo("member1");
}


}

0 comments on commit 0857223

Please sign in to comment.