스프링데이터 + JPA/QueryDSL

31. 순수 JPA -> 스프링 데이터 JPA

sdafdq 2023. 12. 4. 01:50
@Repository
public class MemberJpaRepository {
    .....
    
    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();
    }
}

이걸 스프링 데이터 JPA로 바꿀거임.

 

public interface MemberRepository extends JpaRepository<Member, Long> {
    List<Member> findByUsername(String username);
}

save, findById, findAll은 다 있는거고,

findByUsername은 메소드명으로 쿼리 생성.

 

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

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

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

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

테스트 문제 없이 통과.

 

이거는 다 했고, 이제 QueryDSL 부분과 SpringDataJPA를 결합할 차례