事务概述
1.什么是事务
一件事情有n个组成单元 要不这n个组成单元同时成功 要不n个单元就同时失败就是将n个组成单元放到一个事务中
2. mysql的事务
默认的事务:一条sql语句就是一个事务 默认就开启事务并提交事务
手动事务:
1)显示的开启一个事务:start transaction
2)事务提交:commit代表从开启事务到事务提交 中间的所有的sql都认为有效 真正的更新数据库
3)事务的回滚:rollback 代表事务的回滚 从开启事务到事务回滚 中间的所有的 sql操作都认为无效数据库没有被更新
JDBC事务操作
默认是自动事务:
执行sql语句:executeUpdate() ---- 每执行一次executeUpdate方法 代表 事务自动提交
通过jdbc的API手动事务:
开启事务:conn.setAutoComnmit(false);
提交事务:conn.commit();
回滚事务:conn.rollback();
注意:控制事务的connnection必须是同一个执行sql的connection与开启事务的connnection必须是同一个才能对事务进行控制
DBUtils事务操作
1.QueryRunner
有参构造:QueryRunner runner = new QueryRunner(DataSource dataSource);
有参构造将数据源(连接池)作为参数传入QueryRunner,QueryRunner会从连 接池中获得一个数据库连接资源操作数据库,所以直接使用无Connection参数 的update方法即可操作数据库
无参构造:QueryRunner runner = new QueryRunner();
无参的构造没有将数据源(连接池)作为参数传入QueryRunner,那么我们在使 用QueryRunner对象操作数据库时要使用有Connection参数的方法
使用ThreadLocal绑定连接资源
public class DataSourceUtils {
private static DataSource dataSource = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
// 直接可以获取一个连接池
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
// 获取连接对象
public static Connection getCurrentConnection() throws SQLException {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
// 开启事务
public static void startTransaction() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.setAutoCommit(false);
}
}
// 事务回滚
public static void rollback() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.rollback();
}
}
// 提交并且 关闭资源及从ThreadLocall中释放
public static void commitAndRelease() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.commit(); // 事务提交
con.close();// 关闭资源
tl.remove();// 从线程绑定中移除
}
}
// 关闭资源方法
public static void closeConnection() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.close();
}
}
public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}
}
在上一篇文章中我直接摆上了DataSourceUtils工具类的源码,也没有解释这次借这个部分剖析一下源码。
1.ComboPooledDataSource完整类名是com.mchange.v2.c3p0.ComboPooledDataSource。根据配置文件生成DataSource。
2.ThreadLocal<>这个概念在以前关于线程的一篇文章中写过(链接线程的副本),具体的原理是变量与线程绑定。
3.public static DataSource getDataSource(),public static Connection getConnection()方法分别是返回DataSource和Connection对象。值得注意的是public static Connection getCurrentConnection()方法,它的作用是获得当前线程的connection对象。这个细节会在文章最后的小案例中用到。
4.public static void startTransaction()和public static void rollback()方法是控制事务的,分别是开启事务和事务回滚。其他的方法都是释放资源的。
事务的特性和隔离级别
事务的特性ACID
1)原子性(Atomicity)原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。
2)一致性(Consistency)一个事务中,事务前后数据的完整性必须保持一致。
3)隔离性(Isolation)多个事务,事务的隔离性是指多个用户并发访问数据库时,一个用户的 事务不能被其它用户的事务所干扰,多个并发事务之间数据要相互隔离。
4)持久性(Durability)持久性是指一个事务一旦被提交,它对数据库中数据的改变 就是永久性的,接下来即使数据库发生故障也不应该对其有任何影响。
并发访问问题----由隔离性引起
如果不考虑隔离性,事务存在3中并发访问问题。
- 脏读:B事务读取到了A事务尚未提交的数据 ------ 要求B事务要读取A事 务提交的数据
- 不可重复读:一个事务中 两次读取的数据的内容不一致 ----- 要求的是一个事 务中多次读取时数据是一致的 --- unpdate
- 幻读/虚读:一个事务中 两次读取的数据的数量不一致 ----- 要求在一个事务多 次读取的数据的数量是一致的 --insert delete
事务的隔离级别
- read uncommitted : 读取尚未提交的数据 :哪个问题都不能解决
- read committed:读取已经提交的数据 :可以解决脏读 ---- oracle默认的
- repeatable read:重读读取:可以解决脏读 和 不可重复读 ---mysql默认的
- serializable:串行化:可以解决 脏读 不可重复读 和 虚读---相当于锁表
总结:
概念:
事务的特性ACID
并发问题:脏读、不可重读、虚读\幻读
解决并发:设置隔离级别
read uncommitted
read committed
repeatable read (mysql默认)
serialazable
隔离级别的性能:
read uncommitted>read committed>repeatable read>serialazable
安全性:
read uncommitted<read committed<repeatable read<serialazable
演示代码
事务控制最经典的示例就是银行转账了。那我们就写一个吧。
1.新建工程,导入mysql驱动包,c3p0 jar包。
2.数据库中建立User表,表示银行用户和账户金额,并录入数据
3.配置c3p0配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">123456</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
</default-config>
</c3p0-config>
4.实体User类
public class User {
private String cid;
private String cname;
//账户金额
private double account;
public String getCid() {
return cid;
}
public double getAccount() {
return account;
}
public void setAccount(double account) {
this.account = account;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
5.DataSourceUtils工具类就不再写了。
准备工作就做完了,工程结构比较简单。如图
开始我们正式的代码。
6. MVC结构我们先编写view层的方法。很简单用户1要给用户2转账100(就像爹给儿子转账一样)
public class Transfer {
public static void main(String[] args) {
// 调用业务层的转账方法
bankService service = new bankService();
boolean isTransferSuccess = service.transfer("1", "2", 100);
}
}
7.转账要让银行提供一个方法,于是业务层的转账方法也有了。
public class bankService {
public boolean transfer(String out, String in, double money) {
bankDao dao = new bankDao();
boolean isTranferSuccess = true;
try {
// 转出钱的方法
dao.out(out, money);
// 转入钱的方法
dao.in(in, money);
} catch (Exception e) {
isTranferSuccess = false;
e.printStackTrace();
} finally {
try {
DataSourceUtils.commitAndRelease();
} catch (SQLException e) {
e.printStackTrace();
}
}
return isTranferSuccess;
}
}
8.最后,一切的数据都要存在银行的数据库里保存。
public class bankDao {
// 向账户中减钱
public void out(String out, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set acount=acount-? where cname=?";
Connection connection = DataSourceUtils.getConnection();
runner.update(connection, sql, money, out);
}
// 向账户中加钱
public void in(String in, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set acount=acount+? where cname=?";
Connection connection = DataSourceUtils.getConnection();
runner.update(connection, sql, money, in);
}
}
好了大功告成了!!
我们就测试一波咯
转账之前的数据
运行结果:
数据库:
本以为这样就完成任务了,可是被自己的老板挑刺了。老板加了一行代码,整个业务就乱了。看代码
public class bankService {
public boolean transfer(String out, String in, double money) {
bankDao dao = new bankDao();
boolean isTranferSuccess = true;
try {
// 转出钱的方法
dao.out(out, money);
int i=1/0;
// 转入钱的方法
dao.in(in, money);
} catch (Exception e) {
isTranferSuccess = false;
e.printStackTrace();
}
return isTranferSuccess;
}
}
重新测试一番
结果
数据库:
是呀!如果转账的过程中出现了故障,那么转出去的钱就有可能收不回来了。
9.那我们就分析一下失败额原因:
无参构造:QueryRunner runner = new QueryRunner();
无参的构造没有将数据源(连接池)作为参数传入QueryRunner,那么我们在使 用QueryRunner对象操作数据库时要使用有Connection参数的方法。就是这个Connection出了问题啊,转入转出的connection不是同一个对象啊!!所以会出现可以转出钱但不能转入的问题。好了问题找到了,那就开始解决吧。
10.问题解决一
public class bankService {
public boolean transfer(String out, String in, double money) throws SQLException {
bankDao dao = new bankDao();
boolean isTranferSuccess = true;
Connection connection=DataSourceUtils.getConnection();
try {
// 转出钱的方法
dao.out(connection,out, money);
//int i=1/0;
// 转入钱的方法
dao.in(connection,in, money);
} catch (Exception e) {
isTranferSuccess = false;
e.printStackTrace();
}
return isTranferSuccess;
}
}
public class bankDao {
// 向账户中减钱
public void out(Connection connection, String out, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set account=account-? where cname=?";
runner.update(connection, sql, money, out);
}
// 向账户中加钱
public void in(Connection connection, String in, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set account=account+? where cname=?";
runner.update(connection, sql, money, in);
}
}
测试:
可以完成正常的转账业务。
接下来测试一下故障的情况下能否把钱退回来。
结果:
万幸啊钱退回来了!!!
这时技术总监追过来了,看来又是技术上的问题!!”我破坏了业务与操作的隔离性“技术总监说到。是啊!!这么低级的问题我怎么能犯呢!!
11.问题解决二
不一会我又拿出了我的第二套方案。我的法宝--事务控制。
public class bankDao {
// 向账户中减钱
public void out( String out, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set account=account-? where cname=?";
Connection connection = DataSourceUtils.getCurrentConnection();
runner.update(connection, sql, money, out);
}
// 向账户中加钱
public void in( String in, double money) throws SQLException {
QueryRunner runner = new QueryRunner();
String sql = "update User set account=account+? where cname=?";
Connection connection = DataSourceUtils.getCurrentConnection();
runner.update(connection, sql, money, in);
}
}
public class bankService {
public boolean transfer(String out, String in, double money) throws SQLException {
bankDao dao = new bankDao();
boolean isTranferSuccess = true;
Connection connection=DataSourceUtils.getConnection();
try {
//开启事务
DataSourceUtils.startTransaction();
// 转出钱的方法
dao.out(out, money);
int i=1/0;
// 转入钱的方法
dao.in(in, money);
} catch (Exception e) {
isTranferSuccess = false;
//回滚事务
try {
DataSourceUtils.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
//释放资源
try {
DataSourceUtils.commitAndRelease();
} catch (SQLException e) {
e.printStackTrace();
}
}
return isTranferSuccess;
}
}
测试结果和第一种方法一致,我就不贴图了。
总结:
mysql的事务控制:
开启事务:start transaction;
提交:commit;
回滚:rollback;
JDBC事务控制:
开启事务:conn.setAutoCommit(false);
提交:conn.commit();
回滚:conn.rollback();
DBUtils的事务控制 也是通过jdbc
ThreadLocal:实现的是通过线程绑定的方式传递参数
经过这么长时间的讲解,数据库入门就结束了,下面就开始javaEE的核心部分了。