For performance reasons I'm switching from component scanning to explicitly declaring my beans. So basically I want to remove @EnableJpaRepositories
as it scans for repositories.
My repositories are standard interfaces extending JpaRepository
. How can I declare my repositories?
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
We don't create an interface extending JpaRepository or CrudRepository as usual with Spring Data JPA. Instead, we create a class annotated with @Repository and inject and instance of EntityManager with @PersistenceContext annotation.
Spring then parses the method name and creates a query for it. Here is a simple example of a query that loads a Book entity with a given title. Internally, Spring generates a JPQL query based on the method name, sets the provided method parameters as bind parameter values, executes the query and returns the result.
I agree with @Oliver. However, in time API of Spring Data JPA apparently has changed and in the current version (2.2.3) the snippet should look more like below:
@Configuration
class Config {
@Bean
// assuming userId is String
public JpaRepositoryFactoryBean<UserRepository, User, String> userRepository() {
JpaRepositoryFactoryBean factory = new JpaRepositoryFactoryBean(UserRepository.class);
return factory;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With