Tài liệu mùa xuân ở đây http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations cho ví dụ để thêm chức năng tùy chỉnh vào tất cả các kho lưu trữ hoặc một kho lưu trữ duy nhất, không phải cả hai.Spring Jpa thêm chức năng tùy chỉnh vào tất cả các kho và đồng thời các func khác tùy chỉnh vào một kho lưu trữ
Giả sử tôi muốn thêm một số func tùy chỉnh vào tất cả các kho lưu trữ (sử dụng Nhà máy sản xuất kho lưu trữ tùy chỉnh) và một số khác chỉ cho một kho lưu trữ duy nhất (tài liệu nói sử dụng Giao diện tùy chỉnh và Custom Impl); Làm thế nào tôi có thể đạt được điều này?
Một số mã mẫu mà tôi đã thêm phương thức "setCurrentTenansInSession" vào tất cả các kho lưu trữ; bây giờ tôi muốn thêm phương thức tùy chỉnh, ví dụ: "newCustomMethod", để ona đơn kho lưu trữ (đó là một MyJpaRepository, như cho nhà máy kho tùy chỉnh của tôi). Làm thế nào để tôi làm điều này?
giao diện hành vi tùy chỉnh:
@NoRepositoryBean
public interface MyJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
public void setCurrentTenantInSession(Object object);
}
thực hiện hành vi tùy chỉnh:
public class MultiTenantSimpleJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyJpaRepository<T, ID> {
public void setCurrentTenantInSession(Object object) {
//custom impl
}
}
Tuỳ chỉnh kho bean factory:
public class MultiTenantJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new MultiTenantJpaRepositoryFactory(entityManager);
}
}
Và cuối cùng nhà máy kho tùy chỉnh:
public class MultiTenantJpaRepositoryFactory extends JpaRepositoryFactory {
public MultiTenantJpaRepositoryFactory(EntityManager entityManager) {
super(entityManager);
}
@Override
protected JpaRepository<?, ?> getTargetRepository(RepositoryMetadata metadata, EntityManager entityManager) {
final JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
final SimpleJpaRepository<?, ?> repo = new MultiTenantSimpleJpaRepository(entityInformation, entityManager);
repo.setLockMetadataProvider(LockModeRepositoryPostProcessor.INSTANCE.getLockMetadataProvider());
return repo;
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return MultiTenantSimpleJpaRepository.class;
}
}
Cảm ơn rất nhiều kkamenev! – lincetto
Kể từ 'spring-data-commons' 1.11 chỉ định' base-class = "com.example.CommonCustomRepositoryImpl" 'thay vì thuộc tính' factory-class' không được chấp nhận cho 'jpa: repositories'. Nhà máy là không cần thiết khi xác định lớp cơ sở. –