One to Many JpaTemplate Hibernate Configuration

David Winterfeldt


This is a one-to-many JpaTemplate example using Hibernate that can to find, save, and update a record. There is a Person that has a one-to-many relationship to Address. This example is very similar to One to Many Hibernate Annotation Configuration example since that example was already using javax.persistence annotations to configure the Person and Address beans. Using JpaTemplate can make an easier upgrade path to JPA from an application already using Spring's HibernateTemplate.


This example has the DAO class extend JpaDaoSupport and uses the JpaTemplate, but Spring recommends the native JPA style of coding.


JpaTemplate mainly exists as a sibling of JdoTemplate and HibernateTemplate, offering the same style for people used to it. or newly started projects, consider adopting the native JPA style of coding data access objects instead, based on a "shared EntityManager" reference obtained through the JPA @PersistenceContext annotation.

 -- Spring 2.5.x JPA Documentation

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 HsqldbInitializingDriverManagerDataSource 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 this persistence.xml).

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:component-scan base-package="org.springbyexample.orm.jpa.template.dao" />
    <tx:annotation-driven />
    <bean id="transactionManager"
        <property name="dataSource" ref="dataSource" />
        <property name="entityManagerFactory" ref="entityManagerFactory" />

    <bean id="dataSource"
        <property name="sqlScriptProcessor">
            <bean class="org.springbyexample.jdbc.core.SqlScriptProcessor">
                <property name="charset" value="UTF-8" />
                <property name="sqlScripts">

    <bean id="entityManagerFactory"
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="simple-jpa-template" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />
                <property name="database" value="HSQL" />