One to Many JPA Hibernate Configuration

David Winterfeldt

2009


This is a one-to-many JPA configuration that can to find, save, and update a record. Hibernate is used as the JPA provider. There is a Person that has a one-to-many relationship to Address. This example is very similar to One to Many JpaTemplate Hibernate Configuration and even uses the same javax.persistence annotated beans, but uses the native JPA style for accessing data objects.

1. Spring Configuration

The Person DAO is configured using context:component-scan. Then tx:annotation-driven will configure transactions on any beans with @Transactional, and just after it the JPA transaction manager is setup. The jdbc:embedded-database element is used to initialize the test HSQLDB database. The LocalContainerEntityManagerFactoryBean is configured with the DataSource and for use with Hibernate as the JPA adapter. It also sets the persistenceUnitName attribute to specify which persistence unit to use for this entity manager (multiple examples use the persistence.xml).

PersonDaoTest-context.xml
                
<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jdbc 
                           http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="org.springbyexample.orm.jpa.dao" />
    
    <tx:annotation-driven />

    <bean id="transactionManager" 
          class="org.springframework.orm.jpa.JpaTransactionManager"
          p:entityManagerFactory-ref="entityManagerFactory"/>
    
    <jdbc:embedded-database id="dataSource" type="HSQL">
        <jdbc:script location="classpath:/schema.sql" encoding="UTF-8" />
    </jdbc:embedded-database>    
		
    <bean id="entityManagerFactory" 
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    	  p:dataSource-ref="dataSource"
          p:persistenceUnitName="simple-jpa">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
    </bean>
    
</beans>