Spring + Hibernate

类别:Java 点击:0 评论:0 推荐:

这几天比较空,就来学一学Spring 与 Hibernate(在spring 的英文参考里有这方面的介绍).
下面主要介绍用了Hibernate这后的改变
1、用了Hibernate在配置文件里需增加sessionFactory配置,如下
 <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
        <property name="mappingResources">
             <list>
                <value>net/zdsoft/swh/entity/Company.hbm.xml</value> 
             </list>
         </property>               
         <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
                 <prop key="hibernate.cache.provider_class">net.sf.hibernate.cache.OSCacheProvider</prop>                 
                 <prop key="hibernate.show_sql">true</prop>
                 <prop key="hibernate.use_outer_join">true</prop>                               
                 <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
             </props>
        </property>
        <property name="dataSource"><ref bean="dataSource"/></property>
   </bean>
2、把事务管理用以下代替
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
   </bean>
3、DAO把原来的继承的JDBCDaoSupport改为HibernateDaoSupport
再在配置文件中为DAO增加sessionFactory注入,如下
public class CompanyDAOHibernate extends HibernateDaoSupport implements
        CompanyDAO {
    public Company findById(String id) throws HibernateException {
        Company c = (Company) getHibernateTemplate().load(Company.class, id);
        return c;
    }

    public Company addCompany(Company company) throws HibernateException {
        getHibernateTemplate().save(company);
        return company;
    }

    public void removeCompany(Company company) throws HibernateException {
        getHibernateTemplate().delete(company);
    }

    public Company updateCompany(Company company) throws HibernateException {
        getHibernateTemplate().saveOrUpdate(company);          
        return company;
    }
}
<bean id="companyDAO" class="net.zdsoft.swh.dao.hibernate.CompanyDAOHibernate">
         <property name="sessionFactory"><ref local="sessionFactory"/></property> 
</bean>
其他基本不变

本文地址:http://com.8s8s.com/it/it11921.htm