此处的 Spring 文档http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations提供了将自定义功能添加到所有存储库或单个存储库,而不是两者。
假设我想将一些自定义函数添加到所有存储库(使用自定义存储库工厂 Bean)和其他一些仅添加到单个存储库(文档说使用自定义接口和自定义 Impl);我怎样才能做到这一点?
我在所有存储库中添加了“setCurrentTenansInSession”方法的一些示例代码;现在我想向单个存储库(即 MyJpaRepository,对于我的自定义存储库工厂)添加一个自定义方法,例如“newCustomMethod”。我该怎么做呢?
自定义行为接口:
@NoRepositoryBean
public interface MyJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
public void setCurrentTenantInSession(Object object);
}
自定义行为实现:
public class MultiTenantSimpleJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyJpaRepository<T, ID> {
public void setCurrentTenantInSession(Object object) {
//custom impl
}
}
自定义存储库工厂 bean:
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);
}
}
最后是自定义存储库工厂:
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;
}
}