One to Many Hibernate Annotation Configuration

David Winterfeldt

2008


A simple example using a one-to-many relationship in Hibernate with an Annotation configuration to find, save, and update a record. A Person has a one-to-many relationship with Address.

1. Spring Configuration

The HsqldbInitializingDriverManagerDataSource is used to initialize the test HSQLDB database and the LocalSessionFactoryBean is using to configure Hibernate.

Excerpt from shared-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource"
          class="org.springbyexample.jdbc.datasource.HsqldbInitializingDriverManagerDataSource">
        <property name="sqlScriptProcessor">
            <bean class="org.springbyexample.jdbc.core.SqlScriptProcessor">
                <property name="sqlScripts">
                    <list>
                        <value>classpath:/schema.sql</value>
                    </list>
                </property>
            </bean>
        </property>
    </bean>

...

</beans>
                
            

The annotatedClasses property is used to set a list of Hibernate annotated classes. The Person DAO is configured using Hibernate's session factory.

PersonAnnotationDaoTest-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:org/springbyexample/orm/hibernate3/shared-context.xml"/>
    
    <!-- Override xml session factory imported from shared-context.xml -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.springbyexample.orm.hibernate3.annotation.bean.Person</value>
                <value>org.springbyexample.orm.hibernate3.annotation.bean.Address</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.format_sql=true
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            </value>
        </property>
    </bean>
    
    <bean id="personDao" class="org.springbyexample.orm.hibernate3.annotation.dao.PersonDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>