Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the Hibernate Configuration object from Spring?

Tags:

I am trying to obtain Spring-defined Hibernate Configuration and SessionFactory objects in my non-Spring code. The following is the definition in my applicationContext.xml file:

Code:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">    <property name="hibernateProperties">     <props>       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>       <prop key="hibernate.show_sql">true</prop>       <prop key="hibernate.hbm2ddl.auto">update</prop>       <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>       <prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>     </props>    </property>    <property name="dataSource">     <ref bean="dataSource"/>    </property>     </bean> 

If I now call getBean("sessionFactory"), I am returned a $Proxy0 object which appears to be a proxy for the Hibernate SessionFactory object. But that isn't what I want - I need the LocalSessionFactoryBean itself because I need access to the Configuration as well as the SessionFactory.

The reason I need the Configuration object is that our framework is able to use Hibernate's dynamic model to automatically insert mappings at runtime; this requires that we change the Configuration and rebuild the SessionFactory. Really, all we're trying to do is obtain the Hibernate config that already exists in Spring so that those of our customers that already have that information in Spring don't need to duplicate it into a hibernate.cfg.xml file in order to use our Hibernate features.

like image 514
Wayne Russell Avatar asked Apr 29 '10 09:04

Wayne Russell


People also ask

What is Hibernate configuration object?

The Configuration object is the first Hibernate object you create in any Hibernate application. It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.


1 Answers

One obscure feature of the Spring container is the & prefix:

When you need to ask a container for an actual FactoryBean instance itself, not the bean it produces, you preface the bean id with the ampersand symbol & (without quotes) when calling the getBean method of the ApplicationContext. So for a given FactoryBean with an id of myBean, invoking getBean("myBean") on the container returns the product of the FactoryBean, and invoking getBean("&myBean") returns the FactoryBean instance itself.

So in your case, using getBean("&sessionFactory") should return you the LocalSessionFactoryBean instance itself. Then you can call .getConfiguration() to get the Configuration object.

like image 123
skaffman Avatar answered Sep 20 '22 13:09

skaffman