Spring的声明式事务----Annotation注解方式(1)
这里列一个小的demo工程,直接利用Spring的jdbcTemplate访问Mysql数据库。
工程结构:
数据库中的tbl_student表结构如下:
数据实体类Student.java代码如下:
- package com.mysrc.entity;
- import java.sql.Date;
- public class Student {
- private int id;
- private String name;
- private Date birth;
- private float score;
- public Student() {
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Date getBirth() {
- return birth;
- }
- public void setBirth(Date birth) {
- this.birth = birth;
- }
- public float getScore() {
- return score;
- }
- public void setScore(float score) {
- this.score = score;
- }
- @Override
- public String toString() {
- return "Student [id=" + id + ", name=" + name + ", birth=" + birth
- + ", score=" + score + "]";
- }
- }
数据访问类StudentDao.java代码如下:
- package com.mysrc.dao;
- import java.util.List;
- import org.springframework.jdbc.core.JdbcTemplate;
- import com.mysrc.entity.Student;
- import com.mysrc.entity.StudentRowMapper;
- public class StudentDao {
- private JdbcTemplate jdbcTemplate;
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- public Student getStudentById(int id) {
- return jdbcTemplate.queryForObject(
- "select * from tbl_student where id = ?", new Object[] { id },
- new StudentRowMapper());
- }
- public List<Student> getAllStudent() {
- return jdbcTemplate.query("select * from tbl_student",
- new StudentRowMapper());
- }
- public int insertStudent(Student student) {
- return jdbcTemplate.update(
- "insert into tbl_student(name,birth,score) values(?,?,?)",
- new Object[] { student.getName(), student.getBirth(),
- student.getScore() });
- }
- public int deleteStudent(int id) {
- return jdbcTemplate.update("delete from tbl_student where id = ? ",
- new Object[] { id });
- }
- public int updateStudent(Student student) {
- return jdbcTemplate.update(
- " update tbl_student set name=?,birth=?,score=? where id=? ",
- new Object[] { student.getName(), student.getBirth(),
- student.getScore(), student.getId() });
- }
- }
服务类StudentService.java代码如下:
- package com.mysrc.service;
- import java.sql.Date;
- import java.util.List;
- import org.springframework.transaction.annotation.Isolation;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import com.mysrc.dao.StudentDao;
- import com.mysrc.entity.Student;
- public class StudentService {
- private StudentDao dao;
- public void setDao(StudentDao dao) {
- this.dao = dao;
- }
- @Transactional(propagation = Propagation.NESTED, timeout = 1000, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, noRollbackFor = CustomRuntimeException.class)
- public void doComplexLogic() {
- // select
- List<Student> list = dao.getAllStudent();
- for (Student student : list) {
- System.out.println(student);
- }
- // update
- Student student = list.get(0);
- student.setName("zhejiang");
- dao.updateStudent(student);
- System.out.println("did update temporarily...");
- // int a = 9 / 0; // 遇到异常,整个事务回滚
- // 如果try catch捕获这个异常,那整个事务会顺利执行,不会回滚
- int b = 2;
- if (b > 1) {
- throw new CustomRuntimeException();
- // 事务不会回滚,也就是上面的update操作会提交
- }
- // insert
- student = new Student();
- student.setName("hello");
- student.setBirth(new Date(354778));
- student.setScore(78.9f);
- dao.insertStudent(student);
- System.out.println("did insert...");
- // delete
- dao.deleteStudent(3);
- System.out.println("did delete...");
- }
- class CustomRuntimeException extends RuntimeException {
- public CustomRuntimeException() {
- super();
- }
- public CustomRuntimeException(String msg) {
- super(msg);
- }
- }
- }
doComplexLogic()方法模拟一个复杂的数据库操作过程,方法上加上了@Transactional,其中的各个注解的属性后面再详细研究。网上有人说@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能,这个未验证。
Spring的上下文配置文件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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
- xmlns:tx="http://www.springframework.org/schema/tx">
- <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="url"
- value="jdbc:mysql://127.0.0.1:3306/mytestdb?characterEncoding=utf8" />
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="username" value="root" />
- <property name="password" value="123456" />
- <property name="maxActive" value="100" />
- <property name="maxIdle" value="30" />
- <property name="maxWait" value="1000" />
- <property name="validationQuery" value="select 1" />
- </bean>
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <constructor-arg name="dataSource" ref="basicDataSource">
- </constructor-arg>
- </bean>
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager ">
- <property name="dataSource">
- <ref bean="basicDataSource" />
- </property>
- </bean>
- <bean id="studentDao" class="com.mysrc.dao.StudentDao">
- <property name="jdbcTemplate">
- <ref bean="jdbcTemplate" />
- </property>
- </bean>
- <bean id="studentService" class="com.mysrc.service.StudentService">
- <property name="dao">
- <ref bean="studentDao" />
- </property>
- </bean>
- <tx:annotation-driven transaction-manager="transactionManager" />
- <!--这句话的作用是注册事务注解处理器 -->
- </beans>
测试类MyTester.java代码如下:
- package com.mysrc.test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.mysrc.service.StudentService;
- public class MyTester {
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext(
- "applicationContext.xml");
- StudentService studentService = (StudentService) context
- .getBean("studentService");
- studentService.doComplexLogic();
- }
- }
@Transactional 的所有可选属性如下
属性 | 类型 | 默认值 | 说明 |
propagation | Propagation枚举 | REQUIRED | 事务传播属性 |
isolation | isolation枚举 | DEFAULT | 事务隔离级别 |
readOnly | boolean | false | 是否只读 |
timeout | int | -1 | 超时(秒) |
rollbackFor | Class[] | {} | 需要回滚的异常类 |
rollbackForClassName | String[] | {} | 需要回滚的异常类名 |
noRollbackFor | Class[] | {} | 不需要回滚的异常类 |
noRollbackForClassName | String[] | {} | 不需要回滚的异常类名 |
整个eclipse工程代码文件下载地址:
http://dl.iteye.com/topics/download/6c63c292-88e0-33de-91bb-8b0f38d507e3
Spring的声明式事务----Annotation注解方式(1)的更多相关文章
- Spring的声明式事务----Annotation注解方式(2)
使用步骤: 步骤一.在spring配置文件中引入<tx:>命名空间<beans xmlns="http://www.springframework.org/schema/b ...
- spring4声明式事务--01注解方式
1.在spring配置文件中引入 tx 命名空间 xmlns:tx="http://www.springframework.org/schema/tx" 2.配置事务管理器 < ...
- Spring中声明式事务的注解@Transactional的参数的总结(REQUIRED和REQUIRES_NEW的与主方法的回滚问题)
一.事务的传播行为1.介绍 当事务方法被另一个事务方法调用时,必须指定事务应该如何传播.例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行.2.属性 事务的传播行为可以由传 ...
- 使用注解实现Spring的声明式事务管理
使用注解实现Spring的声明式事务管理,更加简单! 步骤: 1) 必须引入Aop相关的jar文件 2) bean.xml中指定注解方式实现声明式事务管理以及应用的事务管理器类 3)在需要添加事务控制 ...
- Spring声明式事务的实现方式选择(JDK动态代理与cglib)
1.简介 Spring声明式事务的具体实现方式是动态决定的,与具体配置.以及事务代理对象是否实现接口等有关. 2.使用JDK动态代理的情况 在满足下面两个条件时,Spring会选择JDK动态代理作为声 ...
- Spring添加声明式事务
一.前言 Spring提供了声明式事务处理机制,它基于AOP实现,无须编写任何事务管理代码,所有的工作全在配置文件中完成. 二.声明式事务的XML配置方式 为业务方法配置事务切面,需要用到tx和aop ...
- Spring(四)Spring JdbcTemplate&声明式事务
JdbcTemplate基本使用 01-JdbcTemplate基本使用-概述(了解) JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装.spr ...
- Spring之声明式事务
在讲声明式事务之前,先回顾一下基本的编程式事务 编程式事务: //1.获取Connection对象 Connection conn = JDBCUtils.getConnection(); try { ...
- 【Spring】——声明式事务配置详解
项目中用到了spring的事务: @Transactional(rollbackFor = Exception.class, transactionManager = "zebraTrans ...
随机推荐
- NIOSocket Server Client
最近在看Netty框架,顺便写了一下NIO SocketChannel服务端和客户端 Server.java import java.io.IOException; import java.net.I ...
- Arcgis flex 切片地图麻点
在arcgis server中发布地图切片完成后,有时候在访问地图的时候会出现很多麻点, 其实是你切片的时候没有注意到一些选项.... 默认的切片是PNG8,说到这可能就明白了吧,png8的色彩范围: ...
- ArcGIS Enterprise 10.5.1 静默安装部署记录(Centos 7.2 minimal)- 1、安装前准备
安装前准备 上传文件到服务器,x-ftp xshell登陆Centos 检查机器名 修改机器名为:portal.cloud.local 方法一:零时设置,重启后失效,该方法不可取 方法 ...
- Java常用Json库性能对比
Java对于处理JSON数据的序列化与反序列化目前常用的类库有Gson.FastJSON.Jackson.jettison以及json-lib.在这里我们将对这些类库在json序列化与反序列化方面的性 ...
- python大数据
http://blog.csdn.net/xnby/article/details/50782913 一句话总结:spark是一个基于内存的大数据计算框架, 上层包括了:Spark SQL类似Hive ...
- WinDbg:栈帧的含义
转自:http://www.cppblog.com/weiym/archive/2012/06/07/177958.html 栈从高地址向低地址生长, __stcall和__cdecl调用约定都是函数 ...
- CSS和文档流
1. CSS的定位机制有3种:普通流.浮动和定位. 2. 文档流:从上到下,从左到右,一个挨一个的简单或者叫正常布局. 3. 定位:(position) Static:保持文档流. Relati ...
- IFrame安全问题解决办法(跨框架脚本(XFS)漏洞)
最近项目要交付了,对方安全测试的时候检测出高危险漏洞,由于刚参加工作不久,经验不足,未涉及过此方面的东西.经过一番查询和探索,最终解决了这个问题,记录一下. 发现的漏洞为缺少跨框架脚本保护.跨框架脚本 ...
- koa2获取用户ip
调用下面方法即可获取 // koa2 中 req 为 ctx.req const getUserIp = (req) => { return req.headers['x-forwarded-f ...
- tampermonkey利用@require调用本地脚本的方法
比如Tampermonkey上的有个用户脚本a,本来的方法是: 1.直接在Tampermonkey上编辑js,适合高手,但是本人不清楚脚本如何同步,况且不熟练js,在Tampermonkey上写太难了 ...