gruberc wrote:
In Spring Framework, it was more complicated, but I have now the following solution, which might be a bit strange and perhaps not according to the intention of Spring:
In the beans XML file, I use a PropertyPlaceholderConfigurer to replace bean values like "${db}" by the real database. The database name which is determined at runtime is stored in a singleton class. The "db" property is fetched out of this singleton class in an own class that is derived from a PropertiesFactoryBean. For each session to a specific database, I create a new ApplicationContext after setting the database name in my singleton class. Sounds complicated, but it works... Or does somebody have a better idea?
First of all, I assume you mean "for each
SessionFactory to a specific database, I create a new ApplicationContext...".
If you're just doing this to create a LocalSessionFactoryBean for a specific database URL, then there is an easier way: Simply instantiate LocalSessionFactoryBean yourself, invoke its setters, invoke afterPropertiesSet, and fetch the SessionFactory via getObject():
Code:
LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setMappingResources(...);
lsfb.setHibernateProperties(...);
lsfb.afterPropertiesSet();
SessionFactory sf = (SessionFactory) lsfb.getObject();
Instead of setting the database URL via "hibernateProperties", you could also pass a corresponding pre-determined DataSource into setDataSource.
Note that you can use Spring's transaction management and HibernateTemplate with
any SessionFactory, even if manually created. HibernateTransactionManager and HibernateTemplate just take a SessionFactory reference in their respective setters, not caring where it came from - LocalSessionFactoryBean is just a convenient way to create one.
Even if our documentation and our examples focus on using Spring as framework, many parts of it can also be used in a library style. After all, that's the point of an IoC framework: The components do not unnecessarily depend on the framework but typically lend themselves nicely to standalone usage as plain objects.
Juergen