1. 自定义某个 Repository 方法
public interface PersonDao {
void findByIdZi();
}
public class PersonRepsotoryImpl implements PersonDao {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional(rollbackFor = Exception.class)
public void findByIdZi() {
Person person = entityManager.find(Person.class, 11);
System.out.println("-->" + person);
}
}
public interface PersonRepsotory extends
JpaRepository<Person, Integer>,
JpaSpecificationExecutor<Person>, PersonDao {
}
2. 所有Repository 都添加
声明一个接口, 在该接口中声明需要自定义的方法, 且该接口需要继承 Spring Data 的 Repository
@NoRepositoryBean
public interface CommonMethodTest<T, ID extends Serializable>
extends JpaRepository<T, ID>{
void method();
}
提供所声明的接口的实现类. 且继承 SimpleJpaRepository, 并提供方法的实现定义 JpaRepositoryFactoryBean 的实现类
@NoRepositoryBean
public class CommonMethodTestImpl<T, ID extends Serializable>
extends SimpleJpaRepository<T, ID> implements CommonMethodTest<T, ID> {
public CommonMethodTestImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
}
@Override
public void method() {
System.out.println("...METHOD TEST...");
}
}
public class CommonJpaRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable>
extends JpaRepositoryFactoryBean<T, S, ID> {
/**
* Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
*
* @param repositoryInterface must not be {@literal null}.
*/
public CommonJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
@Override
protected RepositoryFactorySupport createRepositoryFactory(
EntityManager entityManager) {
return new CommonRepositoryFactory(entityManager);
}
private static class CommonRepositoryFactory<T, I extends Serializable>
extends JpaRepositoryFactory {
private EntityManager entityManager;
public CommonRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
return new CommonMethodTestImpl<T, I>(
(Class<T>) metadata.getDomainType(), entityManager);
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
return CommonMethodTest.class;
}
}
}