스프링 데이터 Common 2. 인터페이스 정의하기 - KwangtaekJung/inflearn-spring-data-jpa-keesun GitHub Wiki

스프링 데이터 Common: Repository 인터페이스 정의하기

Repository 인터페이스로 공개할 메소드를 직접 일일히 정의하고 싶다면

  • 특정 리포지토리 당
    • @RepositoryDefinition
@RepositoryDefinition(domainClass = Comment.class, idClass = Long.class)
public interface CommentRepository {

    Comment save(Comment comment);

    List<Comment> findAll();
}
@DataJpaTest
class CommentRepositoryTest {

    @Autowired
    CommentRepository commentRepository;

    @Test
    public void crud() {

        Comment comment = new Comment();
        comment.setComment("Hello comment");
        commentRepository.save(comment);

        List<Comment> all = commentRepository.findAll();
        Assertions.assertThat(all.size()).isEqualTo(1);
    }
}
  • 공통 인터페이스 정의
    • @NoRepositoryBean
@NoRepositoryBean
public interface MyRepository<T, ID extends Serializable> extends Repository<T, ID> {

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

    List<T> findAll();
}
public interface CommentRepository extends MyRepository<Comment, Long> {

    Comment save(Comment comment);

    List<Comment> findAll();

    long count();
}
@DataJpaTest
class CommentRepositoryTest {

    @Autowired
    CommentRepository commentRepository;

    @Test
    public void crud() {

        Comment comment = new Comment();
        comment.setComment("Hello comment");
        commentRepository.save(comment);

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

        long count = commentRepository.count();
        assertThat(count).isEqualTo(1);
    }
}
⚠️ **GitHub.com Fallback** ⚠️