通过注解实现Spring 声明式事务管理
小Alan接着上一篇Spring事务管理入门与进阶做一些补充,如果对Spring事务管理还不了解的可以看看上一篇文章。
实例
在我们开始之前,至少有两个数据库表是至关重要的,在事务的帮助下,我们可以实现各种 CRUD 操作。以 Student 表为例,该表是使用下述 DDL 在 MySQL TEST 数据库中创建的。
1 CREATE TABLE Student(
2 ID INT NOT NULL AUTO_INCREMENT,
3 NAME VARCHAR(20) NOT NULL,
4 AGE INT NOT NULL,
5 PRIMARY KEY (ID)
6 );
第二个表是 Marks,我们用来存储基于年份的学生标记。在这里,SID 是 Student 表的外键。
1 CREATE TABLE Marks(
2 SID INT NOT NULL,
3 MARKS INT NOT NULL,
4 YEAR INT NOT NULL
5 );
现在让我们编写 Spring JDBC 应用程序来在 Student 和 Marks 表中实现简单的操作。让我们适当的使用 Eclipse IDE,并按照如下所示的步骤来创建一个 Spring 应用程序:
步骤一:创建一个名为 SpringExample 的项目,并在创建的项目中的 src 文件夹下创建包 com.tutorialspoint。
步骤二:使用 Add JARs 选项添加必需的 Spring 库。
步骤三:在项目中添加其它必需的库 mysql-connector-java.jar,org.springframework.jdbc.jar 和 org.springframework.transaction.jar。如果你还没有这些库,你可以下载它们。
步骤四:创建 DAO 接口 StudentDAO 并列出所有需要的方法。尽管它不是必需的并且你可以直接编写 StudentJDBCTemplate 类,但是作为一个好的实践,我们还是做吧。
步骤五:在 com.tutorialspoint 包下创建其他必需的 Java 类 StudentMarks,StudentMarksMapper,StudentJDBCTemplate 和 MainApp。如果需要的话,你可以创建其他的 POJO 类。
步骤六:确保你已经在 TEST 数据库中创建了 Student 和 Marks 表。还要确保你的 MySQL 服务器运行正常并且你使用给出的用户名和密码可以读/写访问数据库。
步骤七:在 src 文件夹下创建 Beans 配置文件 Beans.xml 。
最后一步:最后一步是创建所有 Java 文件和 Bean 配置文件的内容并按照如下所示的方法运行应用程序。
下面是数据访问对象接口文件 StudentDAO.java 的内容:
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to create
* a record in the Student and Marks tables.
*/
public void create(String name, Integer age, Integer marks, Integer year);
/**
* This is the method to be used to list down
* all the records from the Student and Marks tables.
*/
public List<StudentMarks> listStudents();
}
以下是 StudentMarks.java 文件的内容:
package com.tutorialspoint;
public class StudentMarks {
private Integer age;
private String name;
private Integer id;
private Integer marks;
private Integer year;
private Integer sid;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setMarks(Integer marks) {
this.marks = marks;
}
public Integer getMarks() {
return marks;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getYear() {
return year;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public Integer getSid() {
return sid;
}
}
下面是 StudentMarksMapper.java 文件的内容:
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMarksMapper implements RowMapper<StudentMarks> {
public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {
StudentMarks studentMarks = new StudentMarks();
studentMarks.setId(rs.getInt("id"));
studentMarks.setName(rs.getString("name"));
studentMarks.setAge(rs.getInt("age"));
studentMarks.setSid(rs.getInt("sid"));
studentMarks.setMarks(rs.getInt("marks"));
studentMarks.setYear(rs.getInt("year"));
return studentMarks;
}
}
下面是定义的 DAO 接口 StudentDAO 实现类文件 StudentJDBCTemplate.java:
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO{
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age, Integer marks, Integer year){
try {
String SQL1 = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL1, name, age);
// Get the latest student id to be used in Marks table
String SQL2 = "select max(id) from Student";
int sid = jdbcTemplateObject.queryForInt( SQL2 );
String SQL3 = "insert into Marks(sid, marks, year) " +
"values (?, ?, ?)";
jdbcTemplateObject.update( SQL3, sid, marks, year);
System.out.println("Created Name = " + name + ", Age = " + age);
// to simulate the exception.
throw new RuntimeException("simulate Error condition") ;
} catch (DataAccessException e) {
System.out.println("Error in creating record, rolling back");
throw e;
}
}
public List<StudentMarks> listStudents() {
String SQL = "select * from Student, Marks where Student.id=Marks.sid";
List <StudentMarks> studentMarks=jdbcTemplateObject.query(SQL,
new StudentMarksMapper());
return studentMarks;
}
}
现在让我们改变主应用程序文件 MainApp.java,如下所示:
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
StudentDAO studentJDBCTemplate =
(StudentDAO)context.getBean("studentJDBCTemplate");
System.out.println("------Records creation--------" );
studentJDBCTemplate.create("Zara", 11, 99, 2010);
studentJDBCTemplate.create("Nuha", 20, 97, 2010);
studentJDBCTemplate.create("Ayan", 25, 100, 2011);
System.out.println("------Listing all the records--------" );
List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();
for (StudentMarks record : studentMarks) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.print(", Marks : " + record.getMarks());
System.out.print(", Year : " + record.getYear());
System.out.println(", Age : " + record.getAge());
}
}
}
以下是配置文件 Beans.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 开启注解 -->
<context:annotation-config /> <!-- 注解扫描包路径 -->
<context:component-scan base-package="com.tutorialspoint.*" /> <!-- 通过spring读取配置文件 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="fileEncoding" value="UTF-8"></property>
<property name="locations">
<list>
<value>classpath:conf_db.properties</value>
</list>
</property>
</bean> <!-- Initialization for data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.url.driver}" />
<property name="url" value="${jdbc.url.master}" />
<property name="username" value="${jdbc.username.master}" />
<property name="password" value="${jdbc.password.master}" />
</bean> <!-- Initialization for TransactionManager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 支持事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate" class="com.tutorialspoint.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean> </beans>
以下是数据库配置文件conf_db.properties的内容:
jdbc.url.driver=com.mysql.jdbc.Driver
jdbc.url.master=jdbc:mysql://localhost:3306/TEST
jdbc.username.master=root
jdbc.password.master=123456
最后让我们在StudentJDBCTemplate类上面加上事务注解,此处不建议在Dao层使用事务注解,在平时工作中一般会使用在Service层,小Alan为了演示效果节约时间没有敲Service层代码,请注意,如图:
当你完成了创建源和 bean 配置文件后,让我们运行应用程序。如果你的应用程序运行顺利的话,那么会输出如下所示的异常。在这种情况下,事务会回滚并且在数据库表中不会创建任何记录。
------Records creation--------
Created Name = Zara, Age = 11
Exception in thread "main" java.lang.RuntimeException: simulate Error condition
在删除StudentJDBCTemplate类中create方法抛出异常的代码后,你可以尝试上述示例,在这种情况下,会提交事务并且你可以在数据库中看见记录。
注意:项目jar包如图所示,其中也包含了Spring其它方面的一些jar包,小Alan偷一下懒就没去剔除了,这一块大家可以尝试只留下必要的jar包,以便熟悉Spring所包含的每个jar包在项目中所能够起到的作用,记得把jar包引入项目中才能够运行上述的示例。
@Transactional注解
@Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。
虽然 @Transactional 注解可以作用于接口、接口方法、类以及类方法上,但是 Spring 建议不要在接口或者接口方法上使用该注解,因为这只有在使用基于接口的代理时它才会生效。另外, @Transactional 注解应该只被应用到 public 方法上,这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 @Transactional 注解,这将被忽略,也不会抛出任何异常。
默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使用@Transactional注解进行修饰。
@Transactional参数
参数名称 |
功能描述 |
readOnly |
该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。例如:@Transactional(readOnly=true) |
rollbackFor |
该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。例如: 指定单一异常类:@Transactional(rollbackFor=RuntimeException.class) 指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class}) |
rollbackForClassName |
该属性用于设置需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,则进行事务回滚。例如: 指定单一异常类名称:@Transactional(rollbackForClassName="RuntimeException") 指定多个异常类名称:@Transactional(rollbackForClassName={"RuntimeException","Exception"}) |
noRollbackFor |
该属性用于设置不需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,不进行事务回滚。例如: 指定单一异常类:@Transactional(noRollbackFor=RuntimeException.class) 指定多个异常类:@Transactional(noRollbackFor={RuntimeException.class, Exception.class}) |
noRollbackForClassName |
该属性用于设置不需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,不进行事务回滚。例如: 指定单一异常类名称:@Transactional(noRollbackForClassName="RuntimeException") 指定多个异常类名称: @Transactional(noRollbackForClassName={"RuntimeException","Exception"}) |
propagation |
该属性用于设置事务的传播行为。 例如:@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) |
isolation |
该属性用于设置底层数据库的事务隔离级别,事务隔离级别用于处理多事务并发的情况,通常使用数据库的默认隔离级别即可,基本不需要进行设置 |
timeout |
该属性用于设置事务的超时秒数,默认值为-1表示永不超时 |
结束语:无论正在经历什么,都请不要轻言放弃,因为从来没有一种坚持会被辜负。谁的人生不是荆棘前行,生活从来不会一蹴而就,也不会永远安稳,只要努力,就能做独一无二平凡可贵的自己。
可爱博主:AlanLee
博客地址:http://www.cnblogs.com/AlanLee
本文出自博客园,欢迎大家加入博客园。
通过注解实现Spring 声明式事务管理的更多相关文章
- Spring声明式事务管理基于@Transactional注解
概述:我们已知道Spring声明式事务管理有两种常用的方式,一种是基于tx/aop命名空间的xml配置文件,另一种则是基于@Transactional 注解. 第一种方式我已在上文为大 ...
- Spring声明式事务管理(基于注解方式实现)
----------------------siwuxie095 Spring 声明式事务管理(基于注解方式实现) 以转 ...
- spring 声明式事务管理
简单理解事务: 比如你去ATM机取5000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉5000元钱:然后ATM出5000元钱.这两个步骤必须是要么都执行要么都不执行.如果银行卡扣除了5000块但 ...
- Spring声明式事务管理基于tx/aop命名空间
目的:通过Spring AOP 实现Spring声明式事务管理; Spring支持编程式事务管理和声明式事务管理两种方式. 而声明式事务管理也有两种常用的方式,一种是基于tx/aop命名空间的xml配 ...
- Spring声明式事务管理与配置介绍
转至:http://java.9sssd.com/javafw/art/1215 [摘要]本文介绍Spring声明式事务管理与配置,包括Spring声明式事务配置的五种方式.事务的传播属性(Propa ...
- XML方式实现Spring声明式事务管理
1.首先编写一个实体类 public class Dept { private int deptId; private String deptName; public int getDeptId() ...
- Spring声明式事务管理(基于XML方式实现)
--------------------siwuxie095 Spring 声明式事务管理(基于 XML 方式实现) 以转账为例 ...
- spring声明式事务管理方式( 基于tx和aop名字空间的xml配置+@Transactional注解)
1. 声明式事务管理分类 声明式事务管理也有两种常用的方式, 一种是基于tx和aop名字空间的xml配置文件,另一种就是基于@Transactional注解. 显然基于注解的方式更简单易用,更清爽. ...
- 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:Spring声明式事务管理(基于Annotation注解方式实现)
在 Spring 中,除了使用基于 XML 的方式可以实现声明式事务管理以外,还可以通过 Annotation 注解的方式实现声明式事务管理. 使用 Annotation 的方式非常简单,只需要在项目 ...
随机推荐
- ES6 三层for循环的链式写法
假设有一个很复杂的数据,并且数据嵌套层数很多.如何避免用三层for循环呢? 有以下梨子,我们需要找到val值为12的,这个对象? 'use strict' let groups = [{ conten ...
- PHP-GD库开发手记
创建带有alpha通道的背景输出图像画中文字体获取长宽等比例缩放图片,也可以用于裁切实例代码 创建带有alpha通道的背景 $png = imagecreatetruecolor(800, 600); ...
- pycharm使用github
pycharm使用github 绑定账号 File-settings 在搜索框输入git 会出现github,然后在旁边输入你github的用户名和密码,可以点击”test”测试一下,如果出现: Co ...
- Windows Server 2003、2008、2012系统的安装
说在前面的话 Windows Server 2003,和Windows XP十分相似,可以简单地认为Windows Server 2003是在Windows XP的基础上多了一些服务器管理和操作的功能 ...
- 虚拟机实现finally语句块
1.ret.jsr.jsr_w与returnAddress指令实现finally语句块 当class文件的版本号等于或高于51.0,jsr和jsr_w这两个操作码也不能出现在code数组中. 所有re ...
- QQ空间首页背景图片淡出解析与不足完善
一件事情的发生总是有原因的,当然更多的是对技术本身的追求,一定要搞懂啦,废话不多说,大宝剑直插主题. 起因 以前做过一个xx项目,在登陆界面背景图片中,直接引用了一张大图,css类似于这样(backg ...
- Java对zip格式压缩和解压缩
Java对zip格式压缩和解压缩 通过使用java的相关类可以实现对文件或文件夹的压缩,以及对压缩文件的解压. 1.1 ZIP和GZIP的区别 gzip是一种文件压缩工具(或该压缩工具产生的压缩文件格 ...
- js empty() vs remove()
转自:jQuery empty() vs remove() empty() will remove all the contents of the selection. remove() will r ...
- [作业] Python入门基础--猜年龄
age = 20 while True: try: guess_age = int(input('guess age:')) if guess_age > age: print('Is bigg ...
- 带你走近WebSocket协议
一.WebSocket协议是什么? WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. 二.那为什么我们要用WebSocket协议呢? 了解计算机网络协议的 ...