Spring Data + JPA with multiple datasources but only one set of Repositories

后端 未结 1 2034
不思量自难忘°
不思量自难忘° 2020-12-02 15:06

I\'ve been researching this a bunch today and I\'m starting to think that what I want to do may not be possible, so I am turning to you, o mighty Stackoverflow, for help.

相关标签:
1条回答
  • 2020-12-02 15:27

    If you're really using the different DataSourcees in a multi-tenant kind of way (essentially assigning a request to a DataSource and sticking with it for the entire request) you should have a look at AbstractRoutingDataSource. It essentially provides a way to keep a Map of DataSourcees as well as a callback method to return a key to be used to lookup the DataSource to be used eventually. The implementation of this method usually looks up some thread bound key and return that (or even maps that onto a DataSource map key in turn). You just have to make sure some web component binds that key to the thread in the first place.

    If you have that in place your Spring configuration just sets up a bean for your sub-class of AbstractRoutingDataSource and pipes the map of DataSources into it. Your Spring Data JPA setup stays the default way. The EntityManagerFactoryBean refers to the AbstractRoutingDataSource and you have a single <jpa:repositories /> element only.

    0 讨论(0)
提交回复
热议问题