views:

105

answers:

2

I have MainDB database and unknown number (at compile time) of UserDB_1, ..., UserDB_N databases. MainDB contains names of those UserDB databases in some table (new UserDB can be created at runtime).

All UserDB have exactly the same table names and fields.

How to handle such situation in 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:

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.

A: 

You specify the database when building your SessionFactory (via the connection string of the DataSource). When you want to use another database, simply rebuild the SessionFactory with the new DataSource.

Bozho
Could you please show how to rebuild it? Wouldn't it affect the whole application? I need to switch to another database only temporary for specific queries. And how do I map user tables? I need to provide some table names for mapping but user databases might not exist at compile time, so I can't map them to anything specific.
serg
Also I am using Spring, so this SessionFactory is initialized in config file and wrapped inside TransactionManager.
serg
A: 

Declare and inject different SessionFactory (one per database).

Pascal Thivent