programing

Spring Data JPA에서 엔티티 상속을 처리하는 최선의 방법

starjava 2023. 3. 3. 16:48
반응형

Spring Data JPA에서 엔티티 상속을 처리하는 최선의 방법

JPA 엔티티 클래스가 3개 있습니다.A,B그리고.C계층은 다음과 같습니다.

    A
    |
+---+---+
|       |
C       B

즉, 다음과 같습니다.

@Entity
@Inheritance
public abstract class A { /* ... */ }

@Entity
public class B extends A { /* ... */ }

@Entity
public class C extends A { /* ... */ }

Spring Data JPA를 사용하여 이러한 엔티티의 리포지토리 클래스를 작성하는 가장 좋은 방법은 무엇입니까?

다음 내용을 쓸 수 있다는 것을 알고 있습니다.

public interface ARespository extends CrudRepository<A, Long> { }

public interface BRespository extends CrudRepository<B, Long> { }

public interface CRespository extends CrudRepository<C, Long> { }

하지만 수업 중에A들판이 있다name이 방법을 추가하겠습니다.ARepository:

public A findByName(String name);

다른 2개의 저장소에도 이 방법을 써야 하는데 좀 귀찮아..이런 상황에 대처할 더 좋은 방법이 있을까요?

또 하나 짚고 싶은 점은ARespository읽기 전용 저장소(즉, 확장)여야 합니다.Repositoryclass)를 사용하여 다른 두 저장소는 모든 CRUD 작업을 노출해야 합니다.

가능한 해결책을 알려주세요.

Netglo의 블로그에서 이 투고에서도 설명한 솔루션을 사용했습니다.

이 방법은 다음과 같은 일반 리포지토리 클래스를 만드는 것입니다.

@NoRepositoryBean
public interface ABaseRepository<T extends A> 
extends CrudRepository<T, Long> {
  // All methods in this repository will be available in the ARepository,
  // in the BRepository and in the CRepository.
  // ...
}

이 세 개의 저장소를 다음과 같이 쓸 수 있습니다.

@Transactional
public interface ARepository extends ABaseRepository<A> { /* ... */ }

@Transactional
public interface BRepository extends ABaseRepository<B> { /* ... */ }

@Transactional
public interface CRepository extends ABaseRepository<C> { /* ... */ }

게다가 읽기 전용 저장소를 취득하려면 ,ARepository정의할 수 있습니다.ABaseRepository읽기 전용으로:

@NoRepositoryBean
public interface ABaseRepository<T> 
extends Repository<T, Long> {
  T findOne(Long id);
  Iterable<T> findAll();
  Iterable<T> findAll(Sort sort);
  Page<T> findAll(Pageable pageable);
}

및 에서BRepositorySpring Data JPA도 확장CrudRepository읽기/쓰기 저장소를 얻으려면:

@Transactional
public interface BRepository 
extends ABaseRepository<B>, CrudRepository<B, Long> 
{ /* ... */ }

언급URL : https://stackoverflow.com/questions/27543771/best-way-of-handling-entities-inheritance-in-spring-data-jpa

반응형