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

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

问题描述

我正在研究 Spring Data JPA.考虑下面的示例,我将在默认情况下让所有 crud 和 finder 功能正常工作,如果我想自定义一个 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
    @Lazy
    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天全站免登陆