2012年1月11日 星期三

JPA: How To Dynamic Set up Default Schema for Different Environment on Spring

In the property file:

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="xxxunitname" />
<property name="jpaProperties" ref="hibernateProperties" />
</bean>
<bean id="hibernateProperties"  
     class="com.pa.test.CustomPropertiesFactoryBean">
    <property name="nullable">
        <map>
            <entry key="hibernate.default_schema" value="xxx"/>
        </map>
    </property>
 </bean>

Create your own class:

public class  CustomPropertiesFactoryBean extends PropertiesFactoryBean {

private Map nullable;

public Map getNullable ( )
{
   return nullable;
}

public void setNullable ( Map nullable )
{
   this.nullable = nullable;
}

@Override
protected Object createInstance ( ) throws IOException
{
   Properties result = super.mergeProperties();
 
   String defaultschema =
                     {get from other place like other database or JNDI option or JVM option}
   if (StringUtils.hasText(defaultschema)) {
    result.put("hibernate.default_schema", defaultschema);
   } else {
   for (String key : nullable.keySet())
   {
       if (StringUtils.hasText(nullable.get(key)))
       {
           result.put(key, nullable.get(key));
       }
   }
   }

   return result;
}
}



沒有留言:

張貼留言