user3812693
user3812693

Reputation: 53

Define which entity manager is associated with JpaRepository

I am writing a Spring Boot application which has multiple dataSources and entityManagers and I want to use the JPA CrudRepository interface like:

@Repository public interface Car extends CrudRepository<Car.class, Long> {}.

I get the following error:

Error creating bean with name 'carRepository': Cannot create inner bean '(inner bean)#350d0774' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#350d0774': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource

I have not been able to figure out how to tell the JpaRepositoryFactory which entity manager to use when building the repositories. It defaults to trying to inject an EntityManagerFactory called: entityManagerFactory

Upvotes: 5

Views: 7067

Answers (2)

Omkar Puttagunta
Omkar Puttagunta

Reputation: 4156

Check this documentation on attributes.

Use the @EnableJpaRepositories annotation below on your Java configuration class with entityManagerFactoryRef and transactionManagerRef attributes.

@EnableJpaRepositories(basePackages = {
        "com.myapp.repositories" }, entityManagerFactoryRef = "entityManagerFactoryRef1", transactionManagerRef = "transactionManagerRef1")

Remove @Repository annotation on Car interface. Spring will register it as JPA repository if you specify basePackages attribute.

Upvotes: 5

Prateek Singh
Prateek Singh

Reputation: 1114

what you can do in your spring.xml

    <jpa:repositories base-package="com.a.b.repository"
    entity-manager-factory-ref="yrEntityMAnagerFectorybeanRef"
    transaction-manager-ref="yourTransactionManagerBeanRef"/>

in your EntityManagerFactory bean you will refer your entitymanager bean.

Upvotes: 3

Related Questions