Home > database >  Datasource switching for read-write operations in spring JPA within the same HTTP request
Datasource switching for read-write operations in spring JPA within the same HTTP request

Time:05-31

Using AbstractRoutingDataSource I have implemented read-write Datasource separation in the HTTP request label (essentially assigning a request to a DataSource and sticking with it for the entire request)

In my case, first I have to fetch some data, modify those data and then persist in the database, here first I need READ-ONLY Datasource then UPDATABLE within the same HTTP request. Example:

StudentEntity entity= studentRepository.findById(1);//need read-only datasource
              entity.setName("David");

              entity= studentRepository.save(entity);//need updateable datasource

Could anyone please help me with how can I achieve this? I am struggling for two days.

CodePudding user response:

I have been implement solution like this before. Thinking of 2 verse of database connection. You need 2 datasources bean with 2 jdbcTemplates as well, all need to be named @Bean("beanName") (assign the default one as @Primary for prevent some default process of Spring)

Then @Autowired those 2 beans with @Qualifer("beanName")

But I not sure that this idea is can be apply to the JPA or not.

CodePudding user response:

Found the solution, have to put this in application.properties

spring.jpa.open-in-view=false

Please go to the below link for an explanation.

What is this spring.jpa.open-in-view=true property in Spring Boot?

  • Related