SSH(六)hibernate持久层模板于事务管理

  持久层只要完成数据对数据库增删改查的操作,我们常说的hibernate区别于mybatis是在于他的全自动,而hibernate的全自动则主要体现于

他的模板,一些简单的数据操作我们就不用再去手写sql了,可以通过对hibernate模板的配置去完成。

一、在dao中注入hibernate模板

1.1在dao层继承spring提供的hibernate模板

修改实体product类,让他继承HibernateDaoSupport如图:

1.2在applicationcontext.xml中配置dao层注入hibernate模板

        <!-- 配置dao层:注入hibernate模板 -->
        <bean id="productDao" class="com.ssh.dao.productDao">
        	<!-- ref 值与sessionFactory bean id保持一致 -->
        	<property name="sessionFactory" ref="sessionFactory"></property>
        </bean>

1.3在dao层调用hibernate模板完成数据操作:(模板调用this.getHibernateTemplate().)

	public void sava(product product){
		System.out.println("业务层调用dao层成功!");
		//调用hibernate模板完成保存数据操作
		this.getHibernateTemplate().save(product);
	}

二、添加事务管理

2.1配置事务管理

        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        	<property name="sessionFactory" ref="sessionFactory"></property>
        </bean>

2.2开启事务管理

        <!-- 开启注解事务 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>

2.3在业务层引入事务管理机制@Transactional

 

posted on 2017-06-21 23:58  ckx0709  阅读(366)  评论(0编辑  收藏  举报

导航