How to add custom method to Spring Data JPA

后端 未结 12 1897
盖世英雄少女心
盖世英雄少女心 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

    The accepted answer works, but has three problems:

    • It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
    • You cannot use constructor injection, only @Autowired, that are considered bad practice
    • You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).

    I found a way to make it perfect, though not without using another undocumented Spring Data feature:

    public interface AccountRepository extends AccountRepositoryBasic,
                                               AccountRepositoryCustom 
    { 
    }
    
    public interface AccountRepositoryBasic extends JpaRepository
    {
        // standard Spring Data methods, like findByLogin
    }
    
    public interface AccountRepositoryCustom 
    {
        public void customMethod();
    }
    
    public class AccountRepositoryCustomImpl implements AccountRepositoryCustom 
    {
        private final AccountRepositoryBasic accountRepositoryBasic;
    
        // constructor-based injection
        public AccountRepositoryCustomImpl(
            AccountRepositoryBasic accountRepositoryBasic)
        {
            this.accountRepositoryBasic = accountRepositoryBasic;
        }
    
        public void customMethod() 
        {
            // we can call all basic Spring Data methods using
            // accountRepositoryBasic
        }
    }
    

提交回复
热议问题