Spring中事务管理

来源:互联网 发布:诲汝知之乎的读音 编辑:程序博客网 时间:2024/06/05 18:27
Spring中事务管理一  介绍事务管理1.仅用四个词解释事务    atomic:要么都发生,要么都不发生。   consistent:数据应该不被破坏。   Isolated:用户间操作不相混淆   durable:永久保存2.Spring的使用(1)spring中程序控制事务管理能让你在代码中精确定义事务边界,声明式事务帮助把一个操作从事务规则中分离出来。(2)每种事务管理都充当了对特定平台的事务实现的代理,这样,我们就只需要和spring中的事务打交道,而不用关系实际上事务实现是什么样的,要使用一个事务管理器,你得再上下文中声明它。(3)Spring没有直接管理事务,而是将管理事务的责任委托给某个特定平台的事务实现3.事务的分类和使用事务分为编程式事务管理和声明式事务管理,事务都要在业务中处理,但是在实际开发中事务是用切面来实现的,下面来详细的介绍一下用切面如何实现事务二  切面实现事务在实现事务的时候也是在xml中编写代码来实现,因为要用到切面,所以我们要引入aop schema,引入的方法实在beans标签上写为:xmlns:aop=http://www.springframework.org/schema/aop和http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd这样,aop就可以使用了事务的产生肯定是和增删改查有关系的,我们以在hibernate中的事务为例,配数据源和配hibernate的工厂和hibernate模板类在这里就不多说了,如果有需要,可以看上一篇 --- 征服hibernate。1.首先我们要声明一个事务管理器,来把sessionFactory工厂注入到事务管管理器中,代码为:<!-- 声明事务管理器 --><bean id="hibernateTransactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><!-- 绑定一个sessionFactory --><property name="sessionFactory" ref="sessionFactory"></property></bean>之后,事务的发生地点是在哪呢?什么时候使用事务呢?这时就用到了切面,用一个切面把所有用到的事务都包含进来。2.配置事务的通知<!-- 配置事务的通知 --><tx:advice id="txadvice" transaction-manager="hibernateTransactionManager"><tx:attributes><tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED" /><tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" /><tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED" /><tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" /></tx:attributes></tx:advice>事务的通知配置完了,事务在以上的配置中的某个方法中执行,那么,通知的配置是要有切面的,是哪个切面执行的呢?3.配置一个切面<!-- 配置一个切面 --><aop:config><!-- advisor是切入点和通知的组合体 --><aop:pointcut expression="execution(* cn.csdn.hr.hibernate.service.*.*(..))"id="txPointCut" /><aop:advisor advice-ref="txadvice" pointcut-ref="txPointCut" /></aop:config>其中的切入点是通知实现的地方。这样,我们的事务就配置好了4.举例在删的时候使用事务public void delete(final Admin entity) {// 事务执行操作transactionTemplate.execute(new TransactionCallback() {@Overridepublic Object doInTransaction(TransactionStatus stutus) {// TODO Auto-generated method stubtry {adminDao.delete(entity);//不需要事务的提交} catch (Exception ex) {//只能回滚stutus.setRollbackOnly();}return null;}});}

原创粉丝点击