views:

42

answers:

2

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?

I could create Configuration object and then build SessionFactory, but that would create always a new session factory which wouldn't be very wise.

EDIT:

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)?

A: 

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.

skaffman
I don't know how I can create dynamically new session factories and map them to srping framework, so I can use hibernate session in my DAOs.
newbie
@newbie: You didn't say anything about creating them dynamically. That indeed would be a bad idea. Hibernate is not the tool for this job.
skaffman
Why? One session factory for customer, created dynamically when users log in. I can't see any problems with that, but I just don't know what would be best way to implement it
newbie
+1  A: 

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.

Pascal Thivent
Thanx for this answer, but because all databases are identical I managed to use only one SessionFactory. Now I create Connection object and use method sessionFactory.openSession(connection); to get hibernate session. Now I can dynamically connect to any database I want.
newbie
@newbie: I don't mean to be rude but you should try to give relevant details when asking a question, readers aren't mind readers.
Pascal Thivent
Sorry for that, i try to be more specific next time
newbie
@newbie: No problem, it's just that asking "good" questions will make getting "good" answer more likely :)
Pascal Thivent