JDBC事务管理示例

jopen 10年前

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 parameterautocommitto 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:

  1. JDK 1.7.0_67 (rt.jar includes java.sql package)
  2. Mysql-connector-java 5.1.34
  3. Eclipse Luna
  4. MySQL Community Server 5.6.22

1. Example:

DBConnection.java:

package com.javacodegeeks.jdbc.transactions;    import java.sql.Connection;  import java.sql.DriverManager;  import java.sql.SQLException;    /**   * @author Andres.Cespedes   *   */  public class DBConnection {     private static String DB_URL = "jdbc:mysql://localhost:3307/test";   private static String DB_USER = "admin";   private static String DB_PASSWORD = "admin";     public static Connection getConnection() throws SQLException {    Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);    return connection;   }  }

We useDBConnectiononly to get the connection, any other operation is handled in the main class.

DBTransaction.java:

package com.javacodegeeks.jdbc.transactions;    import java.sql.Connection;  import java.sql.PreparedStatement;  import java.sql.SQLException;    /**   * @author Andres.Cespedes   *   */  public class DBTransaction {     private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)";     /**    * @param args    */   public static void main(String[] args) {    Connection connection = null;    PreparedStatement pstmt = null;    PreparedStatement pstmt2 = null;    try {     connection = DBConnection.getConnection();    } catch (SQLException e) {     System.err.println("There was an error getting the connection");    }    try {     connection.setAutoCommit(false);     System.err.println("The autocommit was disabled!");    } catch (SQLException e) {     System.err.println("There was an error disabling autocommit");    }    // Starts JDBC Transaction    try {     pstmt = connection.prepareStatement(INSERT);     pstmt2 = connection.prepareStatement(INSERT);          pstmt.setInt(1, 1);     pstmt.setString(2, "Madrid");     pstmt.execute();          pstmt2.setInt(1, 2);     pstmt2.setString(2, "Galicia");     pstmt2.execute();          connection.commit();     System.err.println("The transaction was successfully executed");    } catch (SQLException e) {     try {      //We rollback the transaction, atomicity!      connection.rollback();      System.err.println(e.getMessage());      System.err.println("The transaction was rollback");     } catch (SQLException e1) {      System.err.println("There was an error making a rollback");     }    }   }  }

Theconnection.commit()applies all the changes before him. The key is to disable theautocommitand to group the sentences to to manage them in a transaction with a finalcommit.

We try to execute the transaction and this was the result.

The connection is successfully obtained  The autocommit was disabled!  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:

package com.javacodegeeks.jdbc.transactions;    import java.sql.Connection;  import java.sql.PreparedStatement;  import java.sql.SQLException;  import java.sql.Savepoint;    /**   * @author Andres.Cespedes   *   */  public class DBSavePoint {     private static String INSERT = "INSERT INTO test.department (idDepartment, name) VALUES (?, ?)";     public static void insertRow(Connection conn, int idRow, String contentRow)     throws SQLException {    PreparedStatement pstmt = null;    pstmt = conn.prepareStatement(INSERT);    pstmt.setInt(1, idRow);    pstmt.setString(2, contentRow);    pstmt.execute();    pstmt.close();   }     /**    * @param args    */   public static void main(String[] args) {    Connection connection = null;    Savepoint savepoint = null;    try {     connection = DBConnection.getConnection();    } catch (SQLException e) {     System.err.println("There was an error getting the connection");    }    try {     connection.setAutoCommit(false);     System.err.println("The autocommit was disabled!");    } catch (SQLException e) {     System.err.println("There was an error disabling autocommit");    }    // Starts JDBC Transaction    try {     insertRow(connection, 1, "Madrid");     insertRow(connection, 2, "Eibar");     savepoint = connection.setSavepoint("SavePoint1");     insertRow(connection, 3, "Galicia");       connection.commit();     System.err.println("The transaction was successfully executed");    } catch (SQLException e) {     try {      // We rollback the transaction, to the last SavePoint!      connection.rollback(savepoint);      System.err.println(e.getMessage());      System.err        .println("The transaction was rollback to the last savepoint");     } catch (SQLException e1) {      System.err.println("There was an error making a rollback");     }    }   }    }

The methodsetSavepointof classConnectionallows 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 ofSavePointclass.