Blake Rivell
Blake Rivell

Reputation: 13875

Extending CrudRepository and still creating own implementation for custom methods with Spring Data JPA

I have a repository interface that extends CrudRepository to automatically give me all of the basic crud repository functionality.

public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}

Am I still able to add custom repository functions and implement this interface?

Upvotes: 1

Views: 3545

Answers (2)

Paplusc
Paplusc

Reputation: 1130

You can also write you own queries directly in the interface if you extend from JpaRepository<User, Long> by using the annotation @Query

public interface UserRepository extends JpaRepository<User,Long> {

    @Query("select u from User u where u.emailAddress = ?1")
    User findByEmailAddress(String emailAddress);
}

Spring doc: Query annotation

Upvotes: 5

Simon Martinelli
Simon Martinelli

Reputation: 36123

Yes for sure.

There is section in the official documentation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations

The idea is to have an interface for your custom code like this:

interface CustomizedUserRepository {
  void someCustomMethod(User user);
}

Then you need an implementation that ends with Impl:

class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

And finally Spring Data Repo that extends from the custom repo:

interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}

Upvotes: 6

Related Questions