Configuring Hibernate properties in Spring 2

Posted by wsargent Sat, 17 Mar 2007 02:28:00 GMT

Okay, so here’s the deal.

I want to have Hibernate work against Oracle and HSQL. I want it to be configured through Spring, and I want it to not be the schema owner in Oracle.

Setting a different schema owner is easy in Hibernate. You specify this in a spring.properties file, using PropertyPlaceholderConfigurer:

hibernate.default_schema=db

and then you have a properly parameterized Hibernate through Spring:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

&lt;property name="configLocation"&gt;
   &lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt;
&lt;/property&gt;
&lt;property name="dataSource"&gt;
  &lt;ref bean="dataSource" /&gt;
&lt;/property&gt;  
&lt;!-- Overrides what is defined in hibernate.cfg.xml --&gt;
&lt;property name="hibernateProperties"&gt;
  &lt;props&gt;
    &lt;!-- properties chopped for space --&gt;
    &lt;prop key="hibernate.default_schema"&gt;${hibernate.default_schema}&lt;/prop&gt;
  &lt;/props&gt;
&lt;/property&gt;

</bean>

This works fine with Oracle. When you try a default schema with HSQL, it complains, because it doesn’t like the DB.table syntax.

However, setting hibernate.default_schema to an empty string doesn’t work. Even if you somehow hacked PropertyPlaceholderConfigurer to have ${null} as a value (which it won’t do, you can only do it through XML), it wouldn’t work, because a Properties object can’t have a null value.

The way to do this is to use a PropertiesFactoryBean, and define any “conditional” properties through the locations. Then you can define a property as hibernate.config.file=hibernate-oracle and have it pick up hibernate-oracle.properties with the hibernate.default_schema=${hibernate.default_schema} defined in there.

<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">

&lt;property name="properties"&gt;
  &lt;props&gt; 
      &lt;!-- normal properties --&gt;
  &lt;/props&gt;
&lt;/property&gt;
&lt;!-- hibernate.config should be defined somewhere in the spring.properties layers --&gt;
&lt;property name="locations"&gt;
  &lt;list&gt;
      &lt;value&gt;classpath:${hibernate.config.file}.properties&lt;/value&gt;
  &lt;/list&gt;
&lt;/property&gt;

</bean>

<bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>

&lt;!-- normal stuff --&gt;
&lt;property name="hibernateProperties"&gt;
  &lt;ref local="hibernateProperties" /&gt;
&lt;/property&gt;

</bean>