[英]Best way of handling generic entities in Spring MVC(Generics, Reflection, or other)?
[英]Best way of handling entities inheritance in Spring Data JPA
我有三個JPA實體類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);
我也要在其他兩個存儲庫中編寫這樣的方法,這有點煩人。有沒有更好的方法來處理這種情況?
我想要的另一點是ARespository
應該是只讀存儲庫(即擴展Repository
類),而其他兩個存儲庫應該公開所有CRUD操作。
讓我知道可能的解決方案。
我使用了Netgloo博客上這篇文章中描述的解決方案。
我們的想法是創建一個通用的存儲庫類,如下所示:
@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>
{ /* ... */ }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.