Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup Spring Data JPA repositories without component scanning

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?

like image 903
Marcel Overdijk Avatar asked Nov 24 '13 17:11

Marcel Overdijk


People also ask

Which is better CrudRepository or JpaRepository?

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.

What is difference between PagingAndSortingRepository and JpaRepository?

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.

How can we create a custom Repository in Spring data JPA?

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.

How JPA Repository works internally?

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.


1 Answers

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;
  }
}
like image 138
artmiar Avatar answered Oct 04 '22 03:10

artmiar