In this post, we want to talk about JDBC Transactions and how we can manage the operations in a database.
The most popular DBMS like MySQL and Oracle have by default the option autocommit enabled, it means immediately after any DML Operation saves the changes and makes them visible to all users. To use transactions must set the databse parameter autocommit to false.
The management of the database using transaction allows us to maintain consistency in the data, according to his ‘ACID’ property.
Transaction Properties
What we want with Transactions? To Maintain this four properties:
- Atomicity, it’s simple either all operations in database occur, or nothing occurs.
- Consistency, ensures that the database is in a valid state before and after the transaction.
- Isolation, any transaction is independent of another, and your result doesn’t depends of any other.
- Durability, the result of commit a transaction must persist in a non-volatile memory even if occurs a crash or power loss.
Tools
For this example we use:
- JDK 1.7.0_67 (rt.jar includes java.sql package)
- Mysql-connector-java 5.1.34
- Eclipse Luna
- MySQL Community Server 5.6.22
1. Example:
DBConnection.java:
01 |
package com.javacodegeeks.jdbc.transactions; |
03 |
import java.sql.Connection; |
04 |
import java.sql.DriverManager; |
05 |
import java.sql.SQLException; |
08 |
* @author Andres.Cespedes |
11 |
public class DBConnection { |
14 |
private static String DB_USER = "admin"; |
15 |
private static String DB_PASSWORD = "admin"; |
17 |
public static Connection getConnection() throws SQLException { |
18 |
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); |
We use DBConnection only to get the connection, any other operation is handled in the main class.
DBTransaction.java:
01 |
package com.javacodegeeks.jdbc.transactions; |
03 |
import java.sql.Connection; |
04 |
import java.sql.PreparedStatement; |
05 |
import java.sql.SQLException; |
08 |
* @author Andres.Cespedes |
11 |
public class DBTransaction { |
13 |
private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)"; |
18 |
public static void main(String[] args) { |
19 |
Connection connection = null; |
20 |
PreparedStatement pstmt = null; |
21 |
PreparedStatement pstmt2 = null; |
23 |
connection = DBConnection.getConnection(); |
24 |
} catch (SQLException e) { |
25 |
System.err.println("There was an error getting the connection"); |
28 |
connection.setAutoCommit(false); |
29 |
System.err.println("The autocommit was disabled!"); |
30 |
} catch (SQLException e) { |
31 |
System.err.println("There was an error disabling autocommit"); |
33 |
// Starts JDBC Transaction |
35 |
pstmt = connection.prepareStatement(INSERT); |
36 |
pstmt2 = connection.prepareStatement(INSERT); |
39 |
pstmt.setString(2, "Madrid"); |
43 |
pstmt2.setString(2, "Galicia"); |
47 |
System.err.println("The transaction was successfully executed"); |
48 |
} catch (SQLException e) { |
50 |
//We rollback the transaction, atomicity! |
51 |
connection.rollback(); |
52 |
System.err.println(e.getMessage()); |
53 |
System.err.println("The transaction was rollback"); |
54 |
} catch (SQLException e1) { |
55 |
System.err.println("There was an error making a rollback"); |
The connection.commit() applies all the changes before him. The key is to disable the autocommit and to group the sentences to to manage them in a transaction with a final commit.
We try to execute the transaction and this was the result.
1 |
The connection is successfully obtained |
2 |
The autocommit was disabled! |
3 |
The transaction was successfully executed |
Here we should note that if one of the operations does not run correctly, all entries aren’t made and the database remains unchanged.
DBSavePoint.java:
01 |
package com.javacodegeeks.jdbc.transactions; |
03 |
import java.sql.Connection; |
04 |
import java.sql.PreparedStatement; |
05 |
import java.sql.SQLException; |
06 |
import java.sql.Savepoint; |
09 |
* @author Andres.Cespedes |
12 |
public class DBSavePoint { |
14 |
private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)"; |
16 |
public static void insertRow(Connection conn, int idRow, String contentRow) |
18 |
PreparedStatement pstmt = null; |
19 |
pstmt = conn.prepareStatement(INSERT); |
20 |
pstmt.setInt(1, idRow); |
21 |
pstmt.setString(2, contentRow); |
29 |
public static void main(String[] args) { |
30 |
Connection connection = null; |
31 |
Savepoint savepoint = null; |
33 |
connection = DBConnection.getConnection(); |
34 |
} catch (SQLException e) { |
35 |
System.err.println("There was an error getting the connection"); |
38 |
connection.setAutoCommit(false); |
39 |
System.err.println("The autocommit was disabled!"); |
40 |
} catch (SQLException e) { |
41 |
System.err.println("There was an error disabling autocommit"); |
43 |
// Starts JDBC Transaction |
45 |
insertRow(connection, 1, "Madrid"); |
46 |
insertRow(connection, 2, "Eibar"); |
47 |
savepoint = connection.setSavepoint("SavePoint1"); |
48 |
insertRow(connection, 3, "Galicia"); |
51 |
System.err.println("The transaction was successfully executed"); |
52 |
} catch (SQLException e) { |
54 |
// We rollback the transaction, to the last SavePoint! |
55 |
connection.rollback(savepoint); |
56 |
System.err.println(e.getMessage()); |
58 |
.println("The transaction was rollback to the last savepoint"); |
59 |
} catch (SQLException e1) { |
60 |
System.err.println("There was an error making a rollback"); |
The method setSavepoint of class Connection allows to create a checkpoint internally in the transaction, and if a error occurs we can back to the savepoint with all of changes made before.
2. Summary
Here we tried to understand how to manage the JDBC Operations through transactions and how to make check points by means ofSavePoint class.
http://examples.javacodegeeks.com/core-java/sql/jdbc-transaction-management-example/
- spring Transaction Management --官方
原文链接:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html 12. ...
- Spring.NET的中间数据层(Middle Tier Data Access)——事务管理(Transaction management)
简介 Spring.NET为事务管理提供了一个持久化抽象(consistent abstraction ),其优点如下: 为不同事务API,例如ADO.NET,Enterprise Services, ...
- Could not roll back JDBC transaction途径
[异常]接口数量:DM02;错误代码:ERR_EAI_02_014; 错误叙述性说明:当将中间库异常Could not roll back JDBC transaction; nested excep ...
- Java Transaction Management
Just a few weeks ago, I had a discussion with one of my colleagues about how to manage the transacti ...
- Cisco IOS basic system management command reference
absolute : to specify an absolute time for a time-range (in time-range configuration mode) no absolu ...
- JDBC Tutorials: Commit or Rollback transaction in finally block
http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...
- Spring Boot Reference Guide
Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, ...
- 翻译:Spring-Framework-Reference Document:11-Transaction Management
TUESDAY, 07 APRIL Comprehensive transaction support is the most compelling reasons to use the Spring ...
- CSDN上看到的一篇有关Spring JDBC事务管理的文章(内容比较全) (转)
JDBC事务管理 Spring提供编程式的事务管理(Programmatic transaction manage- ment)与声明式的事务管理(Declarative transaction ma ...
随机推荐
- hdu 4722
比赛的时候这道题一直都没出来,承启提醒我之后还是一直WA: 其实规律早就找到了```` 其实这题还可以用数位dp来做,不过从来没写过,以后再贴: 代码: #include<iostream> ...
- ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合
package com.example.s02_e12_json3; import java.lang.reflect.Type; import java.util.Iterator; import ...
- Multi-bit per cell storage
Memories Scaling 其他的的半导体存储器的制程一般2年为一个升级周期,但是nand flash 存储器的制程升级周期和他们比起来只有1年.这种更快的制程升级导致SLC NAND ...
- 【HDOJ】5096 ACM Rank
Treap+set仿函数重定义.每当ac一道题目时,相当于对总时间减去一个大数. /* 5096 */ #include <iostream> #include <string> ...
- 【CF】196 Div.2 D. Book of Evil
显然这个图是一课树,看着题目首先联想到LCA(肯定是可以解的).但是看了一下数据大小,应该会TLE.然后,忽然想到一个前面做过的题目,大概是在一定条件下树中某结点旋转成为根后查询最长路径.结果灵感就来 ...
- java学习之创建线程方法二
我们上一节当中讲到了创建线程的第一种方法,就是继承Thread类,覆写Thread当中的run方法,然后创建子类对象,之后调用对象的start方法启动线程.但是这种方法有一个缺陷,因为我们知道在jav ...
- C#反射之基础应用
今天把反射的东西整理了一下 , 提供了最全面的东西 , 当然也是基础的东西 ,在学好了这一切的基础上 , 大家可以学习反射的具体插件等应用 首先我们建立一个类库 , 将它生成为 reflectPrj ...
- -_-#【video】
视频 HTML5 视频 HTML5的视频格式之争 移动端HTML5<video>视频播放优化实践 后备
- wifi测试相关(iwconfig,WPA Supplicant用法)
iwconfig用法 1.打开无线网卡电源 iwconfig wlan0 txpower no 2.列出区域内的无线网络 iwconfig wlan0 scan 3.假设要连接到网络myhome(即e ...
- Linux停SVN提交时强制写日志
Linux下SVN提交时强制写日志 SVN默认可以不写注释提交,有时候可能忘记写注释,有的人也没有写注释的习惯,导致翻看history的时候都不知道做了哪些更改,可以依照以下步骤修改SVN配置,强制提 ...