开发者

With spring and hibernate, need clarification on how the datasource and session are wired

开发者 https://www.devze.com 2023-01-07 20:42 出处:网络
My DAO\'s are going to extend the HibernateDaoSupport class that spring provides. Now I need to: setup my database connection in web.xml

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 n开发者_如何学Came="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?


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消