Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a specific DataSource for a Repository?

Tags:

Is it possible to assign a specific DataSource to a @Repository?

I'd like to create a test environment where in general I want to use the test-datasource, but a few CrudRepository should operate on a different DB (the production DB; read-only operations).

Can I tell spring which datasource to use for a repository explicit?

public interface MyRepository extends CrudRepository<Customer, Long> {}

like image 882
membersound Avatar asked Apr 01 '15 17:04

membersound


People also ask

How do you configure a DataSource in spring?

To configure your own DataSource , define a @Bean of that type in your configuration. Spring Boot reuses your DataSource anywhere one is required, including database initialization. If you need to externalize some settings, you can bind your DataSource to the environment (see “Section 25.8.

How do you set a DataSource to JpaRepository?

Just create two config files instead of one(one each for each datasource) and add both of them to your main application. Also, give @Primary annotation to the LocalContainerEntityManagerFactoryBean and platformTransactionManager in the config file for primary datasource.

Where do you configure a DataSource in a Spring Boot application?

DataSource configuration is provided by configuration properties entries ( spring. datasource. * ) in application. properties file.


1 Answers

The DataSource and JpaRepository are both tied to an EntityManager. You will have to segregate the repositories into separate packages for your requirement to work.

Here is an example:

<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">   <property name="dataSource">     <bean .../>   </property>   ... </bean> <jpa:repositories base-package="org.example.package1" entity-manager-factory-ref="emf1"/>  <bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">   <property name="dataSource">     <bean .../>   </property>   ... </bean> <jpa:repositories base-package="org.example.package2" entity-manager-factory-ref="emf2"/> 
like image 194
manish Avatar answered Oct 12 '22 02:10

manish