views:

26

answers:

1

My DAO's are going to extend the HibernateDaoSupport class that spring provides.

Now I need to:

  1. setup my database connection in web.xml
  2. Tell spring I am using annotations for hibernate mapping?
  3. wire the session to the HibernateDaoSupport object.

The doc's show a sample xml:

<beans>

  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
  </bean>

  <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
      </value>
    </property>
  </bean>

</beans>

So the 'mydatasource' configures the connection to the database, and the mySessionFactory sets up the session.

What I am confused with is, where in the code are these beans being used?

I want to create a GenericDaoImpl that extendsHibernateDaoSupport. I will then create EntityDaoImpl that extend GenericDaoImpl.

Just confused as to where 'mydatasource' and 'mysessionFactory' are used internally. Shouldn't they both be properties to HibernateDaoSupport?

+3  A: 

Shouldn't they both be properties to HibernateDaoSupport?

Well, SessionFactory should. The DAO won't need the DataSource, since that's used internally by the SessionFactory. Your own code should have no need for the raw DataSource, and so should not have to be injected with it.

Your DAOs (which extend HibernateDaoSupport) need to injected with the SessionFactory bean, e.g.

public class DaoA extends HibernateDaoSupport {
   // business methods here, that use getHibernateTemplate()
}

public class DaoB extends HibernateDaoSupport {
   // business methods here, that use getHibernateTemplate()
}

<bean id="daoA" class="DaoA">
   <property name="sessionFactory" ref="mySessionFactory"/>
</bean>

<bean id="daoB" class="DaoB">
   <property name="sessionFactory" ref="mySessionFactory"/>
</bean>
skaffman
Ah ok, but since I am using a GenericDao that each EntityDao will inherit from, I just need to do this once! cool.
Blankman
So your saying the 'mydatasource' is simply for the 'mysessionfactory' bean to reference, in code there really shouldn't be any references to the 'mydatasource' bean? Its only referenced in the .xml for the sessionFactory correct?
Blankman
Spring is going to require you to declare a <bean> for each GenericDao implementation you want to use - otherwise Spring won't know to create the instance
matt b
@Blankman: See edited answer
skaffman