自定义 Repository 方法

为某一个Repository添加自定义方法

  • 步骤
    1. 定义一个接口:声明要添加的方法。
    2. 提供该接口的实现类:类名需要在声明的Repository后添加Impl,并实现方法
    3. 声明Repository接口,并继承声明的接口
    4. 默认情况下,Spring Data 会在 base-package中查找接口名为Impl 作为实现类 ,也可通过repository-impl-postfix 声明后缀

这里写图片描述


public interface PersonDao {
       void test();
}
public class PersonRepsotoryImpl  implements PersonDao{
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void test() {
        Person person = entityManager.find(Person.class,11);
        System.out.println("--->"+person);
    }
}
 @Test
   public void testCustomRepositoryMethod(){
       personRepsotory.test();
   }
  • 为所有的Repository 添加自实现的方法
    1. 申明一个接口,在该接口中声明需要自定义的方法,且该接口需要继承Spring Data 的Repository
    2. 提供 1 所声明的接口的实现类,且继承SimpleJpaRepository,并提供方法的实现
    3. 定义JpaRepostoryFactoryBean 的实现类,并继承1定义的接口
    4. 修改<jap:repositories><jap:repositories/> 节点的factory-class属性指向3的全类名
    5. 全局的扩展实现类不要用Impl作为后缀,或为全局扩展接口田间@NoRepositoryBean注解告知Spring Data: Spring Data 不把其作为Repository.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章