Using Spring, JPA with Hibernate to access multiple databases/datasources configured in Jboss

前端 未结 1 749
北海茫月
北海茫月 2021-01-21 08:16

I have a requirement where i need to configure a Spring based application to work with two databases. We have two databases, one that we use to keep the live data and the other

相关标签:
1条回答
  • 2021-01-21 08:54

    Spring has exactly what you want - the AbstractRoutingDataSource. See this blog post on how to use it. In your case, you need to switch the datasource during one request, so you'll need to have 2 transactions, switching the datasource between them by changing the datasource indicator on the ThreadLocal:

    1. For these DAOs, demarcate the wrapping Service-layer either with distinct packages, class names, or method names
    2. Indicate to Spring that the Service-layer method calls should run in their own transactional contexts by annotating with @Transactional(propogation=Propogation.REQUIRES_NEW)
    3. Create an Aspect (using AspectJ annotation @Aspect) to fire around the service-layer method calls (using @Around) to set the ThreadLocal value before the method call, and to unset it afterwards
    4. In the @Controller, simply call the Service-layer methods. The Aspect will take care of setting the values to indicate which datasource to use, and the AbstractRoutingDataSource will use that datasource in the context of each transaction.
    0 讨论(0)
提交回复
热议问题