How to Override Spring Data JPA Repository Base Methods

Override spring data save method

As described in my comment overriding 'save' won't achieve your goal. JPA might throw exceptions all over your code. This is one of the problems of JPA.

I guess you could overwrite some central method of Spring to achieve your goal but that really isn't how Spring works.

In stead you basically register your exception handling so, it gets invoked by Spring as desired.

There is an article about this by Baeldung, which looks promising and is valued high by Google.

How to add custom method to Spring Data JPA

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:

  • 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.

Spring JPA custom repository implementation does not work

I'm going to answer my own question after my investigation.

It is not obvious (at least not to me) in Spring's documentation here that the CustomRepository/Impl mechanism must only be used for a single repository. If you want to create some custom implementation to be inherited by multiple repositories, you'll have to customize the base repository, which is going to be used to back all repository beans.

So I ended up adding an int myTestMethod(OffsetDateTime threshold) implementation to the base repository impl BaseRepositoryImpl. This method will be used to back the method declared in MyEntityDataRepository which extends TestRepository. Note: you must let your repository to extend the interface that declares the custom method. Otherwise, the function in the base repository impl will not be available to the repository bean which is a proxy for the interfaces only, not the base repository impl.

Also, you can actually override the base repository's implementation if you customize the same method in the entity repository.

This is not ideal, but it works. I'd hope I can restrict the custom method availability to some repositories only. One way to do that is to split the different "groups" of repositories into separate disjoint packages and declare a distinct base-class for each separate search path. But that may not make sense in many cases.



Related Topics



Leave a reply



Submit