QueryDSL - 순수 JPA 리포지토리와 Querydsl

목차

순수 JPA 리포지토리와 Querydsl

@Repository
public class MemberJpaRepository {

private final EntityManager em;
private final JPAQueryFactory queryFactory;

public MemberJpaRepository(EntityManager em){
this.em = em;
this.queryFactory = 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();
}
}
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> result = memberJpaRepository.findAll();
assertThat(result).containsExactly(member);

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

JPQL QueryDsl 로 변경

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

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

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

public List<Member> findByUsername_Querydsl(String username){
return queryFactory
.selectFrom(member)
.where(member.username.eq(username))
.fetch();
}
@Test
public void basicQueryDsl(){
Member member = new Member("member1", 10);
memberJpaRepository.save(member);

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

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

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