javaspring-dataspring-data-jpa

How to add custom method to Spring Data JPA


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, 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);
}

How can I add a complete custom method with its implementation for the above AccountRepository? Since it's an Interface, I cannot implement the method there.


Solution

  • 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() { ... }
    }
    

    See also: