0

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.

bahadur
  • 24
  • 3

2 Answers2

0

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.

paranaaan
  • 1,626
  • 2
  • 9
  • 17
  • 1
    Thank you paranaaan. Actually, I don't want to handle at the programming level but rather do with configuration using the AOP concept. I have already implemented that using `AbstractRoutingDataSource` (check) but it switches datasource only once for any HTTP request, what I want is to choose datasource for each DB operation. – bahadur May 14 '22 at 05:13
0

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?

bahadur
  • 24
  • 3