스프링데이터 + JPA/QueryDSL

27. 순수 JPA와 QueryDSL

sdafdq 2023. 12. 3. 06:50

먼저 순수 JPA 리포지토리

@Repository
public class MemberJpaRepository {
    private final EntityManager em;
    private final JPAQueryFactory query;

    public MemberJpaRepository(EntityManager em) {
        this.em = em;
        this.query = new JPAQueryFactory(em);
    }

    public void save(Member member){
        em.persist(member);
    }

    public Optional<Member> findById(Long id){
        Member findMember = em.find(Member.class, id);
        return Optional.ofNullable(findMember);
    }

    public List<Member> findAll(){
        return em.createQuery("select m from Member m", Member.class)
                .getResultList();
    }

    public List<Member> findByUsername(String username){
        return em.createQuery("select m from Member m where m.username = :username", Member.class)
                .setParameter("username", username)
                .getResultList();
    }
}

똑같다. 

JPAQueryFactory는 저렇게 생성자에 로직으로 담아도 되고, 아예 저걸 Bean으로 만들어 등록 시켜놔도 된다.

 

Optional.ofNullable, Null일수도 있는 옵셔널 객체로 감싸서 반환

다 똑같다.

 

 

@SpringBootTest
@Transactional
class MemberJpaRepositoryTest {
    @Autowired
    EntityManager em;

    @Autowired
    MemberJpaRepository memberJpaRepository;

    @Test
    public void basicTest(){
        Member member = new Member("member1", 10);
        memberJpaRepository.save(member);

        Member findMember = memberJpaRepository.findById(member.getId()).get();
        assertThat(findMember).isEqualTo(member);

        List<Member> result1 = memberJpaRepository.findAll();
        assertThat(result1).containsExactly(member);

        List<Member> result2 = memberJpaRepository.findByUsername("member1");
        assertThat(result2).containsExactly(member);
    }
}

테스트. 

save 했다가,

id로 찾아보고.

근데 이미 영속성 컨텍스트에 save 하면서 등록되었기 때문에, (persist)

같은 객체를 가져올 것이다.

 

/* select
    m 
from
    Member m */ select
        m1_0.member_id,
        m1_0.age,
        m1_0.team_id,
        m1_0.username 
    from
        member m1_0
        
/* select
    m 
from
    Member m 
where
    m.username = :username */ select
        m1_0.member_id,
        m1_0.age,
        m1_0.team_id,
        m1_0.username 
    from
        member m1_0 
    where
        m1_0.username=?

id로 찾는 건 이미 영속성 컨텍스트에 있어서 쿼리를 안날렸다.

 

하나만 등록해서, 다 member만 있다.

테스트 문제없이 통과.

 

@Repository
public class MemberJpaRepository {
    private final EntityManager em;
    private final JPAQueryFactory query;

    public MemberJpaRepository(EntityManager em) {
        this.em = em;
        this.query = new JPAQueryFactory(em);
    }

    public void save(Member member){
        em.persist(member);
    }

    public Optional<Member> findById(Long id){
        Member findMember = em.find(Member.class, id);
        return Optional.ofNullable(findMember);
    }

    public List<Member> findAll_Querydsl(){
        return query.selectFrom(member)
                .fetch();
    }

    public List<Member> findByUsername_Querydsl(String username){
        return query.selectFrom(member).where(member.username.eq(username))
                .fetch();
    }
}

QueryDSL로 바꿨다. 

QueryDSL도 insert 쿼리메소드가 있긴 하지만,  그것같은 경우는 JPA가 더 간단하여 JPA로 한다.

QueryDSL은 이름처럼 쿼리를 만들어 주는 거다. 

 

username같은 경우는 저렇게 인자로 넣어주면 알아서 바인딩 해 준다. 

 

@Test
public void basicQuerydslTest(){
    Member member = new Member("member1", 10);
    memberJpaRepository.save(member);

    List<Member> result1 = memberJpaRepository.findAll_Querydsl();
    assertThat(result1).containsExactly(member);

    List<Member> result2 = memberJpaRepository.findByUsername_Querydsl("member1");
    assertThat(result2).containsExactly(member);
}

save까지는 로직 자체가 같을 거고,

다 똑같이 테스트 제대로 나온다.

 

/* select
    member1 
from
    Member member1 */ select
        m1_0.member_id,
        m1_0.age,
        m1_0.team_id,
        m1_0.username 
    from
        member m1_0
        
/* select
    member1 
from
    Member member1 
where
    member1.username = ?1 */ select
        m1_0.member_id,
        m1_0.age,
        m1_0.team_id,
        m1_0.username 
    from
        member m1_0 
    where
        m1_0.username=?

나가는 쿼리도 같다.