Spring + Hibernate + JPA +多个数据库 [英] Spring + Hibernate + JPA + multiple databases

查看:240
本文介绍了Spring + Hibernate + JPA +多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring + Hibernate + JPA应用程序。用户在登录时可以从要连接的数据库列表中进行选择(这些是要求)。所有的数据库都有相同的模式,因此将使用相同的实体和DAO。



现在我有一个EntityManager(一直在使用一个数据库)是这样注入DAO的:

$ pre code $ @PersistenceContext
private EntityManager entityManager;

有没有办法让DAO根据参数自动接收entityManager(由Spring管理) /从服务层收到的财产? (Web层发送一种上下文,并且所选数据库的名称/代码/ ID将在那里)。



或者我必须自己管理(创建所有实体管理器,将它们放在地图中,告诉DAO哪一个用于每个调用)?

在问这个问题之前,我做了一些研究,但结果是不确定的 - 大多数问题涉及的模型分布在2个或多个数据库以及跨越多个数据库的事务处理中,但这不适用于我。

在我的情况下,一旦用户连接上,就好像他连接到一个只有一个实体管理器的应用程序,这个实体管理器是他选择的数据库的管理器。数据库的中期会议或任何其他类似的东西之间没有任何切换。



谢谢。

解决方案

这个功能被称为多租户。
$ b $ h Hibernate 4应该支持它开箱即用,但我不确定它是否可以与Spring管理的 EntityManager



集成。或者,最简单的方法是拦截创建数据库连接,可以在 ConnectionProvider 级别或 DataSource 级别上选择合适的数据库,并根据存储在 ThreadLocal 变量。



另请参阅:


I have a Spring + Hibernate + JPA app. The user, when logging in, can choose from a list of DB's to connect to (these are the requirements). All the DB's have the same schema, so the same entities and DAO's will be used.

Right now I have one EntityManager (been working with one database for the moment) that is injected in the DAO like this:

@PersistenceContext
private EntityManager entityManager;

Is there any way to have the DAO receive the entityManager automatically (managed by Spring) based on a parameter/property received from the service layer ? (The web layer sends a kind of context, and the name/code/id of the chosen database will be in there).

Or do I have to manage this myself (creating all the entityManagers, putting them in a map, telling the DAO which one of them to use for each call) ?

I did some research before asking this, but the results were inconclusive - most of the questions dealt with a model spread over 2 or more DB's and transactions spanning multiple DB's, but this is not the case for me.

In my case, once the user is connected, it's just as if he connected to an application that only has one entity manager, the one for the database he selected. There's no switching between DB's mid-session or any other such stuff.

Thank you.

解决方案

This feature is called multi-tenancy.

Hibernate 4 should support it out of the box, though I'm not sure whether it can be integrated with Spring-managed EntityManager.

Alternatively, the easiest way to do it is to intercept creation of database connections, either at ConnectionProvider level or at DataSource level, and choose the appropriate database based on tenant identifier stored in a ThreadLocal variable.

See also:

这篇关于Spring + Hibernate + JPA +多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆