카테고리 없음
[스프링 데이터 JPA] 스프링 데이터 Common 8. 기본 레포지토리 커스터마이징
주멘이
2021. 1. 16. 21:31
모든 리포지토리에 공통적으로 추가하고 싶은 기능이 있거나 덮어쓰고 싶은 기본 기능이 있다면
- JpaRepository를 상속받는 인터페이스 정의
- @NoRepositoryBean
- 기본 구현체를 상속 받는 커스텀 구현체 만들기
- @EnableJpaRepositories에 설정
- repositoryBaseClass
실습 : 어떤 엔티티가 PersistentContext에 들어있는지 확인하는 기능 구현
JpaRepository를 상속하는 CommonRepository 구현
@NoRepositoryBean // 중간 Repository들은 빈 등록이 안되게 하자.
public interface CommonRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
boolean contains(T entity);
}
SimpleJpaRepositry 구현
- spring-data-jpa가 제공해주는 가장 많은 기능을 갖고 있는 핵심 클래스
- JpaRepositry를 상속하면 자동으로 가져오는 클래스이다.
public class CommonRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CommonRepository<T, ID> {
private EntityManager entityManager;
public CommonRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
@Override
public boolean contains(T entity) {
return entityManager.contains(entity);
}
}
메인 Application에 repositoryBaseClass로 설정하기
@SpringBootApplication
@EnableJpaRepositories(queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND
, repositoryImplementationPostfix = "Impl"
, repositoryBaseClass = CommonRepository.class)
@Import(JumenRegister.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
PostRepository가 MyRepositry를 상속받도록 구현
public interface PostRepository extends JpaRepository<Post, Long>, PostCustomRepository<Post>, CommonRepository<Post, Long> {
Page<Post> findByTitleContains(String title, Pageable pageable);
long countByTitleContains(String title);
}
테스트 코드
@Autowired
SendRepository sendRepository;
@Test
public void commonTest() {
Post post = new Post();
post.setTitle("CommonRepository");
assertThat(sendRepository.contains(post)).isFalse(); // transient 상태
sendRepository.save(post);
assertThat(sendRepository.contains(post)).isTrue(); // persistent 상태
}