How to add custom method to Spring Data JPA

后端 未结 12 2083
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:58

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 t

12条回答
  •  误落风尘
    2020-11-22 13:27

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

    public interface AccountRepository 
        extends JpaRepository, 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() { ... }
    }
    

    See also:

    • 4.6 Custom Implementations for Spring Data Repositories

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

提交回复
热议问题