spring中使用aop配置事务

spring的事务配置有5种方式,这里记录其中的一种:基于tx/aop声明式事务配置

在之前spring aop介绍和示例这篇所附代码的基础上进行测试

一、添加save方法

1、在testDao类里添加方法:

/**
 * 保存实体
 */
public void save(testInfo info) {
    sessionFactory.getCurrentSession().save(info);
}

2、在HelloController类里添加方法:

/**
 * 保存实体
 * @param request
 * @return
 */
@RequestMapping("save")
public String save(HttpServletRequest request) {
         
    testInfo info = new testInfo();
    info.setId(request.getParameter("id"));
    info.setName(request.getParameter("name"));
         
    testDao.save(info);
         
    return "redirect:/hello/mysql";
}

二、添加页面

1、添加jar包引用,修改pom.xml文件,加入页面标签的支持:

<!-- web -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

2、修改index3.jsp页面,加入forEach标签:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Insert title here</title>
    </head>
    <body>
        <p>${say}</p>
        <c:if test="${!empty testList}">
           <table border="1" width="100px">
                <tr>
                    <th>列1</th>
                    <th>列2</th>
                </tr>
                <c:forEach items="${testList}" var="item">
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                    </tr>
                </c:forEach>
            </table>
        </c:if>
    </body>
</html>

三、不使用事务运行测试

浏览器访问"http://localhost:8080/demo1/hello/save?id=3&name=123",页面显示:

发现保存后数据没有变化,因为hibernate中如果没有开启事务,在做增删改的时候一直是未提交状态,下面加入事务再进行测试:

四、加入tx/aop事务配置

在spring-context-hibernate.xml配置中添加:

<!-- 定义事务管理器(声明式的事务) -->  
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
     
<!--  声明式容器事务管理 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="save*" propagation="REQUIRED" />
        <tx:method name="*" read-only="true" />
    </tx:attributes>
</tx:advice>
     
<!-- 定义切面 -->
<aop:config expose-proxy="true">
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* org.xs.demo1.testDao.*(..))" />
    <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->
    <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
</aop:config>

五、使用事务后运行测试

浏览器访问"http://localhost:8080/demo1/hello/save?id=3&name=123",页面显示:

添加成功!

实例代码地址:https://github.com/ctxsdhy/cnblogs-example

原文地址:https://www.cnblogs.com/ctxsdhy/p/6399087.html