I have data in different tables but in the same database, all of which have the same schema. Depending on some runtime variable, I want to choose which table to use when querying Hibernate. Is this possible?
Note that I only use Hibernate to read table-data to objects.
A solution (I think) would be one *.hbm.xml-file per table and one SessionFactory per table:
ClassTable1.hbm.xml: <class name="Class" table="table1">...</class>
ClassTable2.hbm.xml: <class name="Class" table="table2">...</class>
ClassTable3.hbm.xml: <class name="Class" table="table3">...</class>
HibernateUtil.java:
getSessionFactoryTable1() {...} // load mapping ClassTable1.hbm.xml
getSessionFactoryTable2() {...} // load mapping ClassTable2.hbm.xml
getSessionFactoryTable3() {...} // load mapping ClassTable3.hbm.xml
Ugly. Especially considering that the only difference between the *hbm.xml-files is the table attribute.
Is there some fancier way of doing this? Ideally with one Class.hbm.xml.
If you are asking this type of question, then this tells me that Hibernate might not be the best tool for your use case.
As an easy solution, why not just programmatically control which hbm.xml files are used in the Configuration in your HibernateUtil.getSessionFactory() method? The Hibernate Configuration object can be programmatically configured.