Suresh Payankannur

Wednesday, May 7, 2014

Overriding Default Methods in Spring Data Repositories

Spring Data provides nice template for standard CRUD methods and the default repository implementations provide support for a variety of back-end data stores. This eliminates the need to create boilerplate code in the application and saves a lot of time.

Adding custom behavior to Spring Data repositories

Implement Custom Behavior
interface UserRepositoryCustom {

  public void someCustomMethod(User user);

class UserRepositoryImpl implements UserRepositoryCustom {

  public void someCustomMethod(User user) {
    // Your custom implementation
Let Spring know about the custom behavior
public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom {

  // Declare query methods here

Selective CRUD operations

By default, Spring Data provides the CRUD operations in Implementing this interface allows complete control of these methods.

But when directly implementing, two CRUD methods must be provided.
  1. findOne
  2. save
The class checks for the existence of these methods in the provided repository implementation. If not found, it will raise an exception.


Post a Comment

Blog Archive

Scroll To Top