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
.
Note | |
---|---|
This example has the DAO class extend |
| ||
-- Spring 2.5.x JPA Documentation |
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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="org.springbyexample.orm.jpa.template.dao" /> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="dataSource" ref="dataSource" /> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="dataSource" class="org.springbyexample.jdbc.datasource.HsqldbInitializingDriverManagerDataSource"> <property name="sqlScriptProcessor"> <bean class="org.springbyexample.jdbc.core.SqlScriptProcessor"> <property name="charset" value="UTF-8" /> <property name="sqlScripts"> <list> <value>classpath:/schema.sql</value> </list> </property> </bean> </property> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <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" /> </bean> </property> </bean> </beans>