views:

113

answers:

1

Hi,

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.

+5  A: 

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.

skaffman
@skaffman Good job!
Arthur Ronald F D Garcia
Perfect, exactly what I needed - thanks!
Wayne Russell