如何向Spring Data JPA添加自定义方法 [英] How to add custom method to Spring Data JPA

查看:930
本文介绍了如何向Spring Data JPA添加自定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Spring Data JPA。考虑下面的示例,我将默认使用所有crud和finder功能,如果我想自定义查找器,那么也可以在界面本身轻松完成。

I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder then that can be also done easily in the interface itself.

@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {

  @Query("<JPQ statement here>")
  List<Account> findByCustomer(Customer customer);
}

我想知道如何添加完整的自定义方法及其实现对于上面的AccountRepository?由于它是一个接口,我无法在那里实现该方法。

I would like to know how can I add a complete custom method with its implementation for the above AccountRepository? Since its an Interface I cannot implement the method there.

推荐答案

您需要为自定义方法创建一个单独的接口:

You need to create a separate interface for your custom methods:

public interface AccountRepository 
    extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }

public interface AccountRepositoryCustom {
    public void customMethod();
}

并为该界面提供实现类:

and provide an implementation class for that interface:

public class AccountRepositoryImpl implements AccountRepositoryCustom {

    @Autowired
    AccountRepository accountRepository;  /* Optional - if you need it */

    public void customMethod() { ... }
}

参见:

请注意,版本之间的命名方案已更改。有关详细信息,请参见 https://stackoverflow.com/a/52624752/66686

Note that the naming scheme has changed between versions. See https://stackoverflow.com/a/52624752/66686 for details.

这篇关于如何向Spring Data JPA添加自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆