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> {}
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.
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.
DataSource configuration is provided by configuration properties entries ( spring. datasource. * ) in application. properties file.
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"/>
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