JDBC for transaction management

Keywords: Java JDBC SQL Database MySQL

JDBC for transaction management

There are four characteristics of a transaction:
Atomicity: refers to that the operations contained in a transaction are regarded as a logical unit
Consistency: the database is in a consistent state before and after the start
Isolation: multiple transactions modified to the database are isolated from each other
The impact on the system after the completion of a persistent transaction is permanent

 

Here is an example: there are two tables, one is the user table and the other is the address table. The user table and the address table are associated through the user ID. Now, to insert a person's information, I need to insert data into two tables, as follows:

insert into tbl_user(id,name,password,email)
                   values(10,'xiongda','123','xiongda@qq.com')
insert into tbl_address(id,city,country,user_id)
                   values(1,'hangzhou','china',10)

When there is a problem, the id of the second statement is duplicate with other data in the table, and there is a primary key conflict. Without transaction management, the user table can only insert data, but the address table cannot.

We regard the insert operation of these two tables as a transaction, which also destroys the consistency of the transaction.

So we need to either insert them all or not, that is, to satisfy the atomicity of transactions.

The code to realize transaction management in JDBC is as follows:

public class TransactionTest {
    public static Connection getConnection(){
        Connection conn=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            conn=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=FALSE&serverTimezone=UTC","root","xb199795");
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    public static void insertUser(Connection conn) throws SQLException {
        String sql="insert into tbl_user(id,name,password,email)"+
                   "values(10,'xiongda','123','xiongda@qq.com')";
            Statement st=conn.createStatement();
            int count=st.executeUpdate(sql);
            System.out.println("Inserted into user table"+count+"Bar record!");
    }
    public static void insertAddress(Connection conn) throws SQLException {
        String sql="insert into tbl_address(id,city,country,user_id)"+
                   "values(1,'hangzhou','china',10)";
            Statement st=conn.createStatement();
            int count=st.executeUpdate(sql);
            System.out.println("Inserted to address table"+count+"Bar record!");
    }
    public static void main(String[] args) {
        Connection conn =getConnection();
        try {
            conn.setAutoCommit(false);
            insertUser(conn);
            insertAddress(conn);
            conn.commit();
        } catch (SQLException e) {
            System.out.println("************Exception in transaction***********");
            e.printStackTrace();
            try {
                conn.rollback();
                System.out.println("*********Transaction rolled back successfully***********");
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }finally {
                try {
                    conn.close();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
}

There is no new data in the user table.

Posted by Mark Baker on Wed, 18 Mar 2020 08:30:03 -0700