博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How to setup multiple data sources with Spring and JPA
阅读量:2439 次
发布时间:2019-05-10

本文共 12690 字,大约阅读时间需要 42 分钟。

转自:http://www.codingpedia.org/ama/how-to-setup-multiple-data-sources-with-spring-and-jpa/

Contents []

In this post I will show you how to setup two or more data sources in a Spring application where the access to the database is done via JPA. It will be a XML-based Spring configuration. To highlight the setup I will use a showcase that builds on an existing demo example I have committed on GitHub, that covers other two posts of mine


  • and

Don’t worry! You don’t have to understand what’s going on in those if you just want to see how the setup for multiple data sources looks like – I’ll do a quick introduction in the first part of the post.

1. Showcase

The demo application used in the posts mentioned presents how to use a REST API to execute CRUD operations against a back-end db, delivering podcasts. For the demo’s sake I’ll say a client of the REST API also needs resources(podcasts) from a “legacy” system – she needs to combine them with the ones from the actual system and present them to their users.

For that I will implement two new read operations that will GET the podcast(s) from the “legacy” system. The new REST facade layer – PodcastLegacyRestService – that delivers “legacy” resources will use the same data access layer to highlight the use of multiple data sources.

Now let’s see how to configure and code multiple data sources with Spring and JPA:

2. Configuration

2.1. Persistence.xml

The first thing I did was to modify the persistence.xml file by adding a new persistence unit that will correspond to the “legacy” entityManager, managing the new “legacy” data source:

Note: The persistence unit defines a set of all entity classes that are managed by EntityManagerinstances in an application. This set of entity classes represents the data contained within a single data store.

Because I am using Spring you can see the configuration of the persistence unit in the persistence.xmlis very lean. The actual configuration of the entity managers takes places in the Spring’s application context of the application. See the next section for the details.

2.2. Spring Appplication Context

In the Spring application context I just added new beans for the entity manager, transaction manger and datasource:

Note the persistenceUnitName property of the entityManagerFactory is pointing to the corresponding persistence unit.

Here’s a quick recap of the main configured beans:

  • entityManagerFactoryLegacy(org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean) is aorg.springframework.beans.factory.FactoryBean that creates a JPAjavax.persistence.EntityManagerFactory according to JPA’s standard container bootstrap contract. This is the most powerful way to set up a shared JPA EntityManagerFactory in a Spring application context; the EntityManagerFactory can then be passed to JPA-based DAOs via dependency injection. Note that switching to a JNDI lookup or to aLocalEntityManagerFactoryBean definition is just a matter of
    configuration!
    As with LocalEntityManagerFactoryBean, configuration settings are usually read in from a META-INF/persistence.xml config file, residing in the class path, according to the general JPA configuration contract. However, this FactoryBean is more flexible in that you can override the location of the persistence.xml file (as here the case), specify the JDBC DataSources to link to, etc. Furthermore, it allows for pluggable class instrumentation through Spring’sorg.springframework.instrument.classloading.LoadTimeWeaver abstraction, instead of being tied to a special VM agent specified on JVM startup.
  • transactionManagerLegacy (org.springframework.orm.jpa.JpaTransactionManager) is aorg.springframework.transaction.PlatformTransactionManager implementation for a single JPAjavax.persistence.EntityManagerFactory. Binds a JPA EntityManager from the specified factory to the thread, potentially allowing for one thread-bound EntityManager per factory.SharedEntityManagerCreator and JpaTemplate are aware of thread-bound entity managers and participate in such transactions automatically. Using either is required for JPA access code supporting this transaction management mechanism.
    This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually throughorg.springframework.transaction.jta.JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.

2.3. In code

As mentioned before to highlight the multiple data source configuration in code I extended the DAO layer class with methods to access the “legacy” system:

You see here how you can use multiple entity managers in the same class. And we that we conclude the configuration example of accessing multiple data sources.

Code Tip – you can best see the differences to the code with one data source configuration by having a look at my GitHub commit for this post at 

2.3.1. Using @Transactional

If you are using transactions via the @Transactional annotation you need to specify the transaction manager you are using:

3. Testing it – optional

To test the new “legacy” functionality you can start the jetty server configured in the pom.xml, file by issuing the following maven command in the root directory of the project:

Once Jetty is started execute GET operations on the following URIs:

to get all podcasts, or respectively a specific podcast from the “legacy” system.
You can also have look at my video on how to test a REST API with the 
width="420" height="315" src="http://www.youtube.com/embed/_71JXeP5FNc" allowfullscreen="allowfullscreen" frameborder="0" style="box-sizing: border-box; max-width: 100%;">
Well, that’s it. You’ve learned how to configure multiple a Spring application to access multiple data sources via JPA.

If you’ve found it useful, please help it spread by sharing it on Twitter, Google+ or Facebook. Thank you! Don’t forget also to check out  – you’ll find for sure interesting podcasts and episodes. We are grateful for 

4. Resources

4.1. Codingpedia

4.2. GitHub

  • ( encapsulates code for this post)

4.3. Web

转载地址:http://gsgmb.baihongyu.com/

你可能感兴趣的文章
Cg FAQ (转)
查看>>
在access中增加农历支持模块. (转)
查看>>
增加一个判断内存变量存在的函数 (转)
查看>>
ASP文件上传神功 第二重(招势图加内功心法) (转)
查看>>
JSR227:J2EE数据绑定及数据访问标准 (转)
查看>>
Sun ONE Studio 4 Mobile Edition开发MIDlet入门 (转)
查看>>
Jbuilder8开发J2ee学习笔记(2) (转)
查看>>
Makefile编写小说(一) (转)
查看>>
NeHe的opengl教程delphi版(3)----着色 (转)
查看>>
ORACLE SQL性能优化系列 (二) (转)
查看>>
控件treeview的使用 (转)
查看>>
运用VC或Java对Office进行编程操作 (转)
查看>>
Linux Shell 裡一些很少用到卻很有用的指令 (转)
查看>>
一套日本软件开发的详细设计说明书格式(一) (转)
查看>>
第10章 模型管理视图 (转)
查看>>
第7章 活 动 视 图 (转)
查看>>
“管家婆”软件用于维修管理 (转)
查看>>
第13章 术 语 大 全 (8) (转)
查看>>
第13章 术 语 大 全 (9) (转)
查看>>
人月神话读书笔记(二) (转)
查看>>