[{"data":1,"prerenderedAt":15},["ShallowReactive",2],{"$f3i0203swpii7z":3},{"slug":4,"title":5,"date":6,"excerpt":7,"tags":8,"source":11,"aiAssisted":12,"readingTime":13,"html":14,"disabled":12},"read-write-responsibility-segregation-2024Feb24","Read and Write Responsibility Segregation","2024-02-24","Separating read and write data access in Spring Boot microservices",[9,10],"Spring Boot","Architecture","LinkedIn",false,"2 min read","\u003Cp>Google Cloud databases such as Cloud SQL for PostgreSQL and AlloyDB are fully managed PostgreSQL services that can offer distinct instances for reading and writing data. Out of the box, read instances offer performance improvements when querying data.\u003C\u002Fp>\n\u003Cp>When using separate read and write database instances with a Spring Boot microservice and JPA, you may need to create two separate data sources and two repository packages.\u003C\u002Fp>\n\u003Cp>For example:\u003C\u002Fp>\n\u003Cpre>\u003Ccode class=\"language-java\">@EnableJpaRepositories(\n    basePackages = { &quot;com.example.repository.readwrite&quot; },\n    entityManagerFactoryRef = &quot;readWriteEntityManagerFactory&quot;,\n    transactionManagerRef = &quot;readWriteTransactionManager&quot;)\npublic class ReadWriteDataSourceConfig {\n}\n\n@EnableJpaRepositories(\n    basePackages = { &quot;com.example.repository.read&quot; },\n    entityManagerFactoryRef = &quot;readEntityManagerFactory&quot;,\n    transactionManagerRef = &quot;readTransactionManager&quot;)\npublic class ReadDataSourceConfig {\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>The reason for this is that when the \u003Ccode>ReadWriteDataSourceConfig\u003C\u002Fcode> and \u003Ccode>ReadDataSourceConfig\u003C\u002Fcode> beans are created, the repository bean cannot be registered with the same name. To resolve this, create read and write repositories in separate packages.\u003C\u002Fp>\n\u003Cp>This is good for read and write responsibility segregation.\u003C\u002Fp>\n\u003Cp>Then one might realize that it makes sense to continue and create two distinct services and REST controllers as well, and perhaps continue even further by using read and write model classes as described in the CQRS pattern.\u003C\u002Fp>\n\u003Cp>This leads to cleaner code implementation and is easier to read and maintain.\u003C\u002Fp>\n\u003Cp>\u003Ca href=\"https:\u002F\u002Fwww.linkedin.com\u002Fposts\u002Fkamlesh18_read-and-write-responsibility-segregation-activity-7167299567783272449-JLfm\">Originally published on LinkedIn\u003C\u002Fa>.\u003C\u002Fp>\n",1792023078692]