How to Configure Spring beans.xml File: Collection properties and EntityManagerFactory Examples

Java beans in Spring can also have their collection properties populated in the beans.xml file. The collection properties here mean things like List, Map and Array.

For example, if you want to create a JPA EntityManagerFactory with a set of connection properties, these properties can be configured in beans.xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="entityManagerFactoryCreator" 
    class="com.mytechtip.example.EntityManagerFactoryCreator">
    <property name="persistenceUnitName" value="HRMN_Repository"/>
    <property name="jpaProperties">
      <props>
        <prop key="openjpa.ConnectionURL">the_url</prop>
        <prop key="openjpa.ConnectionDriverName">the_driver_class_name</prop> 
        <prop key="openjpa.ConnectionUserName">the_user_name</prop>
        <prop key="openjpa.ConnectionPassword">the_password</prop>
      </props>
    </property>
  </bean>
</beans>

Here, jpaProperties in the actual java class “EntityManagerFactoryCreator” is an instance of Properties. And you can just use this properties to create EntityManagerFactory.

    // ...
    private Properties jpaProperties;
    //...
    public void setJpaProperties(Properties prop) {
        this.jpaProperties = prop;
    }
    // ...
    public EntityManagerFactory create() {
        return Persistence.createEntityManagerFactory("myPersistenceUnit", prop);
    }

Actually, Spring already have something similar for you to access EntityManagerFactory with ease. The beans used for the task are:

  • org.springframework.orm.jpa.LocalEntityManagerFactoryBean
  • org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean

More information / examples can be found here about the support of JPA entity manager factory creatation in Spring.

Leave a Reply

Spam Protection by WP-SpamFree