Spring事务 基于配置的实现方式
2016-12-19 20:40
423 查看
Spring事务 基于配置的实现方式
上一篇博客地址:http://blog.csdn.net/u013704342/article/details/53589474《Spring 事务原理》
源代码地址:http://download.csdn.net/detail/u013704342/9715759 《Spring基于XML方式配置事务 》
1.我们先创建一个接口
2.创建一个实现类
3.创建一个rowMapper
5.创建一个spring配置文件
6.创建一个测试类
说一下需要注意的几个点:
1.配置no-rollback-for="RuntimeException" 需要注意。因为配置了以后,运行时的所有异常是不会回滚的。
2.在service中捕获的异常,要抛出,或者手动回滚。如果异常不抛出,spring则提交事务,这样就会出现脏数据。
3.配置事务切面的时候,可以用query*,get*等方式,代替方法全称。配置过的方法,都受到spring的管理。
上一篇博客地址:http://blog.csdn.net/u013704342/article/details/53589474《Spring 事务原理》
源代码地址:http://download.csdn.net/detail/u013704342/9715759 《Spring基于XML方式配置事务 》
1.我们先创建一个接口
package com.test.service.interfaces; import com.test.bean.UserInfoBean; public interface UserInfoServiceInterface { /** *添加信息到userInfo表中 */ void addUserInfo(UserInfoBean userInfoBean); /** *删除userInfo表中的数据 */ void deleteUserInfo(UserInfoBean userInfoBean); /** *更新userInfo表中的数据 */ void updateUserInfo(UserInfoBean userInfoBean); /** *查询userInfo表中的数据 */ void queryUserInfo(UserInfoBean userInfoBean); /** *查询userinfo表中的数据 */ void queryUserInfo2(UserInfoBean userInfoBean); }
2.创建一个实现类
package com.test.service.imp; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import com.test.bean.UserInfoBean; import com.test.service.interfaces.UserInfoServiceInterface; public class UserInfoServiceImp implements UserInfoServiceInterface { /** *spring jdbcTemplate */ private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public void addUserInfo(UserInfoBean userInfoBean){ System.out.println("add方法:addUserInfo(UserInfoBean userInfoBean)"); String sql ="insert into userinfo(account,name,password)values(?,?,?)"; this.jdbcTemplate.update(sql, new Object[]{userInfoBean.getAccount(),userInfoBean.getName(),userInfoBean.getPassword()}); // 该异常用来测试事务是否生效 // throw new NullPointerException("空指针异常"); } @Override public void deleteUserInfo(UserInfoBean userInfoBean){ System.out.println("delete方法:deleteUserInfo(UserInfoBean userInfoBean)"); String sql = "delete from userinfo where id=?"; this.jdbcTemplate.update(sql, new Object[]{userInfoBean.getId()}); // 该异常用来测试事务是否生效 // throw new NullPointerException("空指针异常"); } @Override public void updateUserInfo(UserInfoBean userInfoBean) { System.out.println("update方法:updateUserInfo(UserInfoBean userInfoBean)"); String sql = "update userinfo set account=?, name=? where id=?"; // 如果对sql 捕获异常 不向外抛出去的话,则spring会给你commint数据 //这样数据库就会产生脏数据了! 所以 在处理sql的时候 要事务回滚就需要抛出异常信息。 try { this.jdbcTemplate.update(sql, new Object[]{userInfoBean.getAccount(),userInfoBean.getName(),userInfoBean.getId()}); //返回一个运行时异常 // throw new RuntimeException("运行时异常"); // throw new NullPointerException("空指针"); } catch (Exception e) { // 如果你配置了no-rollback-for="RuntimeException" 运行时异常不回滚的话~ 则再次抛出运行时异常也没用, // 所以配置的时候需要注意一下。 // throw new NullPointerException("空指针"); } } /* (non-Javadoc) * @see com.test.service.imp.UserInfoServiceInterface#queryUserInfo(com.test.bean.UserInfoBean) */ @Override public void queryUserInfo(UserInfoBean userInfoBean){ String sql = "select account from userinfo where id=?"; UserInfoBean bean = new UserInfoBean(); String a = (String) this.jdbcTemplate.queryForObject(sql, new Object[]{userInfoBean.getId()}, String.class); // bean = (UserInfoBean) this.jdbcTemplate.queryForObject(sql, new Object[]{userInfoBean.getId()}, userInfoBean.getClass()); System.out.println("查询信息:"+a); } /* (non-Javadoc) * @see com.test.service.imp.UserInfoServiceInterface#queryUserInfo2(com.test.bean.UserInfoBean) */ @Override public void queryUserInfo2(UserInfoBean userInfoBean) { String sql ="select * from userinfo where id=?"; List<UserInfoBean> list= this.jdbcTemplate.query(sql, new Object[]{userInfoBean.getId()}, new UserInfoRowMapper()); if(null!=list){ for(UserInfoBean user :list){ System.out.println("查询信息2:"+user.getAccount()); } } } }
3.创建一个rowMapper
package com.test.service.imp; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.test.bean.UserInfoBean; public class UserInfoRowMapper implements RowMapper { @Override public Object mapRow(ResultSet arg0, int arg1) throws SQLException { UserInfoBean userInfoBean = new UserInfoBean(); userInfoBean.setId(arg0.getInt("id")); userInfoBean.setAccount(arg0.getString("account")); userInfoBean.setName(arg0.getString("name")); userInfoBean.setPassword(arg0.getString("password")); return userInfoBean; } }4.创建一个bena。
package com.test.bean; public class UserInfoBean { private int id ; private String account; private String name; private String password; //getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
5.创建一个spring配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 配置数据库链接 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 配置驱动地址 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <!-- 配置url地址 --> <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring_test?useUnicode=true&characterEncoding=UTF-8" ></property> <!-- 配置userName --> <property name="username" value="root"></property> <!-- 配置密码 --> <property name="password" value="root"></property> <!-- 配置初始化的连接池数量 --> 4000 <property name="initialSize" value="5"></property> <!-- 配置连接池最大链接数量 --> <property name="maxActive" value="500"></property> <!-- 配置连接池最大空闲链接数量 --> <property name="maxIdle" value="2"></property> <!-- 配置连接池最小保留的链接数量 当空闲的连接数少于阀值时,连接池就会预申请去一些连接, 以免洪峰来时来不及申请 --> <property name="minIdle" value="2"></property> </bean> <!-- 注入DataSource 到 事务管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置事务切面 --> <aop:config> <!-- 配置切入点 定义在service包和所有子包里的任意类的任意方法的执行:execution(* com.test.service..*.*(..)) 或者 * *..*service..*.*(..)--> <aop:pointcut id="transactionPointcut" expression="execution(* *..*service..*.*(..))"/> <!-- 关联通知--> <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/> </aop:config> <!-- 配置事务通知 id为 txAdvice 事务管理器为txManager --> <tx:advice id="txAdvice" transaction-manager="txManager"> <!-- 配置事务通知的属性 --> <tx:attributes> <!-- 配置执行的方法 所有 以query 和get开头的方法 为只读模式,并且不打开事务--> <tx:method name="query*" read-only="true" propagation="NOT_SUPPORTED"/> <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/> <!-- 配置所有以update 开头的方法都打开事务 并且10秒超时 并且遇到运行时异常的时候不回滚 --> <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" timeout="10" no-rollback-for="RuntimeException" /> <!-- 配置所有delete开头的方法都打开事务 并且10秒后超时 --> <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" timeout="10"/> <!-- 配置所有add开头的 方法都打开事务 --> <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED" timeout="10"/> <!-- 配置所有以save开头的方法都打开事务 --> <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" timeout="10"/> <!-- 如果觉得麻烦 可以配置 <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="10" />这样 --> <!-- 所有方法都开启事务 隔离性为default ropagation="REQUIRED"(传播属性为必须的) 超时为10秒 不配置 rollback-for 则所有的 异常都回滚--> <!-- <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="10" /> --> </tx:attributes> </tx:advice> <bean id="userService" class="com.test.service.imp.UserInfoServiceImp"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
6.创建一个测试类
package com.test.junit; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.test.bean.UserInfoBean; import com.test.service.interfaces.UserInfoServiceInterface; public class TestSpring { @Test public void test() { try { ApplicationContext conn = new ClassPathXmlApplicationContext("Spring-JDBC.xml"); UserInfoServiceInterface userSerivce = (UserInfoServiceInterface)conn.getBean("userService"); UserInfoBean userInfoBean = new UserInfoBean(); userInfoBean.setAccount("test00123"); userInfoBean.setName("测试2"); userInfoBean.setPassword("123456"); // 插入数据 userSerivce.addUserInfo(userInfoBean); // 删除数据 userInfoBean.setId(7); userSerivce.deleteUserInfo(userInfoBean); //更新数据 userInfoBean.setId(6); userSerivce.updateUserInfo(userInfoBean); // 查询数据对象的方式 userSerivce.queryUserInfo(userInfoBean); // 查询数据list的方式 userSerivce.queryUserInfo2(userInfoBean); } catch (Exception e) { e.printStackTrace(); } // fail("Not yet implemented"); } }到这里结束。
说一下需要注意的几个点:
1.配置no-rollback-for="RuntimeException" 需要注意。因为配置了以后,运行时的所有异常是不会回滚的。
2.在service中捕获的异常,要抛出,或者手动回滚。如果异常不抛出,spring则提交事务,这样就会出现脏数据。
3.配置事务切面的时候,可以用query*,get*等方式,代替方法全称。配置过的方法,都受到spring的管理。
相关文章推荐
- spring(3) 属性转换为对象
- SpringEl表达式,以及Property文件属性的注解注入到bean中
- [课堂笔记]一.Java概述
- Spring与Ibatis整合入门
- java代码中查看字符集方法
- Java-NowCoder-图片整理
- java基础2
- RxJava操作符系列六
- Java读入时的一些小问题--next()和nextLine()
- myEclipse
- eclipse搭建Android开发环境遇到的坑
- Eclipse常用快捷键(不定时更新)
- Java语言基础(十一): 二维数组
- MyBatis 缓存
- Java基础恶补——内存泄露、内存溢出
- Spring
- java ‘转圈’打印二维数组
- PAT1064:Complete Binary Search Tree (Java实现)
- Spring的整体部署
- eclipse各版本介绍