[英]Need to map classes to different databases at runtime in Hibernate
I have MainDB
database and unknown number (at compile time) of UserDB_1
, ..., UserDB_N
databases. 我有
MainDB
数据库,并且在编译时, UserDB_1
,..., UserDB_N
数据库的数量未知。 MainDB
contains names of those UserDB
databases in some table (new UserDB
can be created at runtime). MainDB
在某些表中包含那些UserDB
数据库的名称(可以在运行时创建新的UserDB
)。
All UserDB
have exactly the same table names and fields. 所有
UserDB
的表名和字段都完全相同。
How to handle such situation in Hibernate? 在Hibernate中如何处理这种情况? (database structure cannot be changed).
(数据库结构无法更改)。
Currently I am planning to create generic User
classes not mapped to anything and just use native SQL for all queries: 目前,我正计划创建未映射到任何内容的通用
User
类,而仅对所有查询使用本机SQL:
session.createSQLQuery("select * from " + db + ".user where id=1")
.setResultTransformer(Transformers.aliasToBean(User.class));
Is there anything better I can do? 有什么我可以做的更好的吗? Ideally I would want to have mappings for UserDB tables and relations and use HQL on required database.
理想情况下,我希望具有UserDB表和关系的映射,并在所需的数据库上使用HQL。
You specify the database when building your SessionFactory
(via the connection string of the DataSource
). 在构建
SessionFactory
时,可以指定数据库(通过DataSource
的连接字符串)。 When you want to use another database, simply rebuild the SessionFactory
with the new DataSource
. 当您要使用另一个数据库时,只需使用新的
DataSource
重建SessionFactory
即可。
声明并注入不同的SessionFactory
(每个数据库一个)。
Read this article on Hibernate blog: http://in.relation.to/Bloggers/MultitenancyInHibernate 在Hibernate博客上阅读此文章: http : //in.relation.to/Bloggers/MultitenancyInHibernate
Steve says that it is better to use a ConnectionProvider than separate SessionFactory. 史蒂夫说,最好使用ConnectionProvider而不是单独的SessionFactory。
Remember to disable second level cache. 切记禁用二级缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.