在写代码之前我们需要了解一下什么是事务管理以及geCurrentSession跟openSession的区别?
1.事务就是对一系列的数据库操作(比如插入一条或多条数据)会进行统一的提交或回滚操作,如果插入成功,那么 一起成功,如果在数据操作的过程中发生异常(则为失败),也会回滚之前所有的操作。 2.数据库数据出现问题开发中为了避免这种情况一般都会进行事务管理。 3.在JDBC中是通过Connection对象进行事务管理的,默认是自动提交事务,可以手工将自动提交关闭,通过commit方法进行提交,rollback方法 进行回滚,如果不提交,则数据不会真正的插入到数据库中。 4.Hibernate中是通过Transaction进行事务管理,处理方法与JDBC中类似。 5.Spring中也有自己的事务管理机制,一般是使用TransactionMananger进行管理,可以通过Spring的注入来完成此功能。 getCurrentSession跟openSession的区别: 1.getCurrentSession自动关闭会话对象,通过上下文来判断是否需要创建session对象,如果我们没有创建session对象,则会自动帮我们创建一个session对象,如果已有session对 象,则继续使用同一个对象,当我们方法不在使用的时候会自动的帮我们关闭。 2.openSession手动关闭会话对象,手动创建session对象,每次打开的时候都会调用一个新的对象。需要调用close()方法来关闭session对象。 本例用的是Spring注入来完成的事务管理机制(还是以水果系统为例)在原来的基础上进行修改: 先来到我们的FruitDaoImpl类将我们原来的代码删掉或是注释掉
package fruit.dao; import java.util.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import fruit.entity.Fruit; //给我们的dao类定义类注解 //并给出非单例模式 @Repository @Scope("prototype")public class FruitDaoImpl implements FruitDao{ //给FruitDao定义一个sessionFactory的变量 //给FruitDao类注入SessionFaction类 @Autowired private SessionFactory sf; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public List showAllFruit() { Session session = sf.getCurrentSession(); //Session session = sf.openSession(); //开启事务 //session.getTransaction().begin(); //定义hql查询语句(form Fruit)Fruit指的是实体类的类名而不是表名。 Query<Fruit> query = session.createQuery("from Fruit"); List<Fruit> allFruitList = query.getResultList(); /*提交事务并关闭session对象 * session.getTransaction().commit(); session.close();*/ return allFruitList; } @Override public String delSingleFruit(Integer id) { Fruit fruit1=new Fruit(); fruit1.setFruitName("苹果"); fruit1.setFruitType("仁果类"); fruit1.setListed(new Date()); fruit1.setSeason("秋季"); //System.out.println("来了"); //Session session=sf.openSession(); Session session = sf.getCurrentSession(); //定义hql删除语句 @SuppressWarnings("unchecked") Query<Fruit> query= session.createQuery("from Fruit where id=:myid"); query.setParameter("myid",id); List<Fruit> deleteList=query.getResultList(); //判断删除的数据是否存在(存在则为1)存在则删除,如果为0则什么也不做 if(deleteList.size()==1){ Fruit fruit=deleteList.get(0); session.delete(fruit); session.save(fruit1); //在控制台打印输出 System.out.println("删除对象:"+fruit.getFruitName()+ " Id:"+fruit.getFruitType()+fruit.getListed()+fruit.getSeason()); //这边用到了事物管理(把这段代码从dao删除掉) /*session.getTransaction().begin(); session.getTransaction().commit(); session.close();*/ } //session.close(); return "deleteOK"; } }
applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- 原理:自动注入processor解析器,用来解析注解 --> <!-- <context:annotation-config/> --> <context:component-scan base-package="fruit" /> <!-- 引入外部属性文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 注入连接池,包含了数据库用户名,密码等等信息 --> <property name="dataSource" ref="myDataSource" /> <!-- 配置Hibernate的其他的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.connection.autocommit">false</prop> <!-- 开机自动生成表 --> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingResources"> <list> <value>fruit/entity/Fruit.hbm.xml</value> </list> </property> </bean> <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> <!-- 每300秒检查所有连接池中的空闲连接 --> <property name="idleConnectionTestPeriod" value="300"></property> <!-- 最大空闲时间,900秒内未使用则连接被丢弃。若为0则永不丢弃 --> <property name="maxIdleTime" value="900"></property> <!-- 最大连接数 --> <property name="maxPoolSize" value="2"></property> </bean> <!-- 配置事务 --> <!-- 配置hibernate的局部事务管理,使用hibernateTransactionManager类 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 配置HibernateTransactionManager时需要注入的sessionFactory对象的引用 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置通知Spring容器对注解@Transaction的Bean处理 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置事务增强处理,指定事务管理器 <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="mod*" propagation="REQUIRED" /> 必须要配置开启事务,不然getCurrentSession()会获取不到 <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> 配置一个切入点,匹配fruit.dao下所有类执行的方法 <aop:pointcut id="interceptorPointCuts" expression="execution(* fruit.dao.*.*(..))" /> 指定在poincut切入点应用txAdvice事务增强处理 <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config> --> </beans>
当我们添加这一段代码的时候,需要去到我们的service,给我们的FruitServiceImpl添加注解@Transaction:
来到ServiceImpl类:
package fruit.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import fruit.dao.FruitDao; import fruit.entity.Fruit; //给我们的action类定义类注解 //并给出非单例模式 @Transactional(readOnly=true) @Service @Scope("prototype") public class FruitServiceImpl implements FruitService{ //定义一个dao的变量 //给FruitService类注入FruitDao类 @Autowired private FruitDao fd; @Override public List showAllFruit() { //在service这边调用dao的showAllFruit方法 List<Fruit> allFruitList=fd.showAllFruit(); return allFruitList; } @Override public String delSingleFruit(Integer id) { //当可以删除时,调用DAO直接删除 return fd.delSingleFruit(id); } }
编译结果如下:
来到这边,说明我们的程序编译是正常的,jsp页面如下:
最后再写一下Spring基于aop/tx配置的声明式事务管理跟@Transactional注解的区别:
1.aop/tx配置声明式事务管理耦合性低,可读性低,表达较详细,灵活性也高。(aop/tx配置声明式事务管理代码如下:)
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <!-- 配置HibernateTransactionManager时需要注入的sessionFactory对象的引用 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!--配置事务增强处理,指定事务管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="mod*" propagation="REQUIRED" /> <!--必须要配置开启事务,不然getCurrentSession()会获取不到--> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <!--配置一个切入点,匹配fruit.dao下所有类执行的方法--> <aop:pointcut id="interceptorPointCuts" expression="execution(* fruit.dao.*.*(..))" /> <!--指定在poincut切入点应用txAdvice事务增强处理--> <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务传播特性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="get*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置哪些类的哪些方法参与事务 -->
<aop:config>
<aop:advisor pointcut="execution(* com.sdjz.eshop.service.*..*.*(..))" advice-ref="transactionAdvice" />
</aop:config>
2.@Transactional注解可读性较高,内容分散不利于统一的管理和维护,耦合性较高。(.@Transactional注解代码如下:)
因为service要调用dao类的方法,所以在service类添加@Transactional注解。