0

I have an application where I want to define two datasources, one for read and one for write :

# Master Database
spring.datasource.url= jdbc:mysql://mysite.com/mydb
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# Replica Database
spring.read.datasource.url= jdbc:mysql://mysite1.com/mydb
spring.read.datasource.username=user
spring.read.datasource.password=pass
spring.read.datasource.driver-class-name=com.mysql.jdbc.Driver

I have defined two data sources/entity managers/transaction managers

but with spring data only one will be selected for one repository (?) I know I can segregate the entities and repos and configure different ems to work with different packages (repos/entities).

Can I use different ems for same repo? Say, by doing @Transactional(value="readTransactionManager") on one method and @Transactional on the second?

Bottom line : can I configure to spring use multiple data sources for same entities?

Any help is appreciated. I might be asking a stupid question.

Sachin Sharma
  • 1,446
  • 4
  • 18
  • 37

1 Answers1

0

Can I use different ems for same repo ? -- no, you can't. You can use a db cluster to that and in that case you can connect in one cluster, one db server responsible for read (usually slave) and another for write (usually master). You should not aware of which server you want to connect in cluster mode. Though it seems a little bit slow for heavy usage. Or you can use multiple EMS for different datasource as you said - I know I can segregate the entities and repos and configure different ems to work with different packages (repos/entities).

See the comment as @skaffman said in the link, Spring multiple @Transactional datasources

Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34