Spring Data JPA05 自定义某个 Repository 方法

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;
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值