스프링데이터 + JPA/스프링 데이터 JPA

7. 공통 인터페이스 적용

sdafdq 2023. 11. 19. 16:18

적용..

 

그냥 봤던대로,

public interface TeamRepository extends JpaRepository<Team, Long> {
}

public interface 리포지토리명 extends JpaRepository<엔티티타입, PK타입> {
}

끝.

 

@Test
public void basicCRUD(){
    Member member1 = new Member("member1", 10);
    Member member2 = new Member("member2", 11);

    memberRepository.save(member1);
    memberRepository.save(member2);

    Member findMember1 = memberRepository.findById(member1.getId()).get();
    Member findMember2 = memberRepository.findById(member2.getId()).get();

    assertThat(findMember1).isSameAs(member1);
    assertThat(findMember2).isSameAs(member2);

    List<Member> members = memberRepository.findAll();
    assertThat(members).containsOnly(member2, member1);

    long count = memberRepository.count();
    assertThat(count).isEqualTo(2);

    memberRepository.delete(member1);
    Optional<Member> deletedMember = memberRepository.findById(member1.getId());
    assertThat(deletedMember.isEmpty()).isTrue();
}

이거, memberJpaRepository로 원래 했던건데, 그냥 memberJpaRepository를 memberRepository로 그대로 바꿔서 테스트 진행.

문제없음. 정상동작하고 테스트 다 통과 함.

 

우리가 기존에 만들었던,

@Repository
@RequiredArgsConstructor
public class MemberJpaRepository {
    private final EntityManager em;

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

    public Member find(Long id){
        return em.find(Member.class, id);
    }

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

    public void delete(Member member){
        em.remove(member);
    }

    public long count(){
        return em.createQuery("select count(m) from Member m", Long.class)
                .getSingleResult();
    }

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

이거 자체가 그냥 JpaRepository 상속받아서 만든 Spring Data Jpa와 거의 유사하다고 보면 됨.

이래서 Spring Data Jpa는 Jpa를 편하게 사용하도록 만든거라는 거임. 실제로 내부에서도 jpa로 동작 하는거고.