반응형
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
읽기 전용 저장소(즉, 확장)여야 합니다.Repository
class)를 사용하여 다른 두 저장소는 모든 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);
}
및 에서BRepository
Spring 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
반응형
'programing' 카테고리의 다른 글
wpdb를 사용하여 데이터를 삽입하는 방법 (0) | 2023.03.03 |
---|---|
Angular JS, 해결 및 알 수 없는 공급자 (0) | 2023.03.03 |
머티리얼 UI에서 컴포넌트를 중앙에 배치하여 응답성을 높이는 방법 (0) | 2023.03.03 |
ASP에서 HTTP OPTIONS 동사를 지원하는 방법.NET MVC/WebAPI 응용 프로그램 (0) | 2023.03.03 |
효소는 onChange 이벤트를 시뮬레이트합니다. (0) | 2023.03.03 |