Hibernate using multiple databases

大城市里の小女人 提交于 2019-12-04 09:54:10

I need to have multiple databases for different customers. How can I handle multiple databases with Hibernate? Are there any good examples how to do this?

You'll have indeed to create multiple SessionFactory (one per database).

Now I can get hibernate Configuration object when user logs in, but how can I create/get session factory with that object so that there would be only one session factory for one database (of course if multiple databases are used at the same time, then there can be more than one session factory)?

Use some unique Map<SomeKey, SessionFactory>. If a SessionFactory hasn't been created yet, build it and store it in the map.

I had the same problem. I solved it like this:

First of all, there should be different cfg.xml files for different databases. Then simply use Configuration object of the Hibernate whenever you want to connect to your second database.

Configuration config = new Configuration().configure("<complete path to your cfg.xml file>");
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();

I found this here : http://www.coderanch.com/t/468821/ORM/java/If-hibernate-cfg-xml-has

I am pretty sure that this can be extended to more than 2 databases. Hope this helps.

A Hibernate SessionFactory can only handle one DataSource at a time, and generally speaking each DataSource refers to one and only one database. So if you need multiple databases, then the simplest solution is almost certainly multiple SessionFactory instances.

I'm not sure why you think this would not be wise, though, it seems fair enough to me.

Some RDBMS allow limited cross-database references, which may allow you to do something with Hibernate and a single DataSource, but you haven't told us anything about your database setup.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!