Spring/스프링 데이터 JPA

[스프링 데이터 JPA] 스프링 데이터 Common 2. 인터페이스 정의하기

주멘이 2021. 1. 16. 20:23

Repository marker Interface를 이용하여 메서드를 직접 정의하여 사용하는 것

  • JpaRepository에서 들어오는 기능들이 싫고 직접 정의해서 사용하고 싶다면.

공통 인터페이스 정의

/**
 * Custom Repositry Define.
 * */
@NoRepositoryBean
public interface MyRepository<T, Id extends Serializable> extends Repository<T, Id> {

    <E extends T> E save(E entity);

    List<T> findAll();

    long count();
}

공통 인터페이스를 extend 하고 사용할 수 있다

public interface CommentRepository extends MyRepository<Comment, Long>{
}

 

공통 인터페이스를 상속한 CommentRepository 테스트 

@DataJpaTest
class CommentRepositoryTest {

    @Autowired
    CommentRepository commentRepository;

    @Test
    public void crudRepositoryTest() {
        //When
        Comment comment = new Comment();
        comment.setComment("Hello Comment");
        commentRepository.save(comment);	

        //Then
        List<Comment> all = commentRepository.findAll();
        assertThat(all.size()).isEqualTo(1);

        //When
        long count = commentRepository.count();
        //Then
        assertThat(count).isEqualTo(1);

    }

}