views:

88

answers:

2

Hi,

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.

+2  A: 

Could you use annotations instead of defining the class in an hbm.xml file? You might be able to write a base class that defines all the column mappings (since you said they don't change), then extend it once for each of your "table1", "table2", "table3" scenarios where each of the child classes has a different annotation that points to the correct table for that class. Might work.

Jim Tough
Interesting. I didn't think about that. However, I believe this would result in different Classed; one for each table?
Emore
+1  A: 

Depending on some runtime variable, I want to choose which table to use when querying Hibernate.

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.

matt b
Thanks, this probably sounds like the least bad solution, if using Hibernate. I'll give it a go!By the way, if you know some other tool that might be a better fit, drop a comment :)
Emore
@Emore, well Hibernate is a great ORM tool but it really shines and is intended to manage the full lifecycle of your objects - creation, updating, and reading. If you only ever need to read objects you might be swatting a fly with a sledgehammer - Spring's JdbcTemplate and iBatis SqlMaps are two other options that might be more lightweight. In both, you basically specify the SQL query to run and then a mapping (in Spring JdbcTemplate, usually within the code; in iBatis, usually in XML) from columns in the resultset to fields in your objects
matt b
Ah, I see. I'll definitely read up on those, even though I'll probably stay with Hibernate for learning- and consistency reasons. Thanks!
Emore