Transaction and JDBC transaction isolation levels

business-related theories

 MySQL transaction isolation level: http://mj4d.iteye.com/blog/1744276

Transaction:

       A unit of concurrency control, a sequence of operations defined by the user. These operations are either done or not done, and they are an inseparable unit of work. Through transactions, sql server can bind together a logically related set of operations so that the server maintains the integrity of the data. A transaction usually begins with a begin transaction and ends with a commit or rollback. Commint means commit, that is, commit all operations of the transaction. Specifically, all the updates to the data in the transaction are written back to the physical database on the disk, and the transaction ends normally. Rollback means rollback, that is, if some kind of failure occurs during the operation of the transaction, the transaction cannot continue, and the system undoes all completed operations on the database in the transaction and rolls back to the state where the transaction started.

 

 

1. Characteristics of transactions (ACID): 

1) Atomic: A transaction is the logical unit of work of the database, and it must be an atomic unit of work. For its data modification, either all of them are executed, or all of them are not executed

2) Consistency: When a transaction is completed, all data must be in a consistent state. In a relational database, all rules must be applied to the modification of a transaction to maintain the integrity of all data.

 3) Isolation: The execution of a transaction cannot be affected by other transactions.

                      Transactions must be isolated from each other to prevent concurrent reads and writes of the same data.

 

 4) Durable: Once a transaction is committed, the operation of the transaction is permanently stored in the DB. Even performing a rollback operation at this point cannot undo the changes.

Atomicity (Atomic) Modifications to data either all or none of them.

Consistent The data state remains consistent before and after the transaction is executed.

Isolated (Isolated) The processing of one transaction cannot affect the processing of another transaction.

Durable The transaction ends and its effects persist in the database.

 

2. Problems that may be caused by concurrent transaction processing

Dirty read A transaction reads data that has not yet been committed by another transaction.

Non-repeatable read (non-repeatable read) The operation of one transaction causes another transaction to read different data twice before and after

Phantom read The operation of one transaction causes the result data volume of the two queries before and after another transaction to be different.

Example:

When transactions A and B are executed concurrently,

When transaction A is updated, transaction B selects to read the data that A has not yet submitted. At this time, transaction A rolls back, and the data read by B is invalid "dirty" data.

After transaction B selects to read the data, the update operation of transaction A changes the data selected by transaction B. At this time, transaction B reads the data again, and finds that the two data before and after are different.

After transaction B selects to read the data, transaction A inserts or deletes a record that satisfies the select conditions of transaction A. At this time, transaction B selects again and finds that the record that did not exist in the previous query ("phantom"), or the previous record A record of is missing.

 

Auto-commit transactions : Each individual statement is a transaction. A commit is implied after each statement. (default) 

Explicit transaction : Begin with begin transaction display and end with commit or rollback.

 

Implicit Transaction : When a connection operates in implicit transaction mode, the instance of the SQL Server database engine will automatically start a new transaction after committing or rolling back the current transaction. There is no need to describe the beginning of things, just commit or rollback each transaction. But each transaction still explicitly ends with a commit or rollback. After the connection has the implicit transaction mode set to open, an implicit transaction is automatically started when the database engine instance executes any of the following statements for the first time: alter table, insert, create, open, delete, revoke, drop, select, fetch, truncate table, grant, update The transaction will remain valid until a commit or rollback statement is issued. After the first transaction is committed or rolled back, the next time the connection executes any of the above statements, the database engine instance will automatically start a new transaction. The instance will continue to generate implicit transaction chains until implicit transaction mode is turned off.

 

 

 

 Types of Java Transactions

    There are three types of Java transactions: JDBC transactions, JTA (Java Transaction API) transactions, and container transactions.

    1. JDBC transaction

    JDBC transactions are controlled with Connection objects. The JDBC Connection interface ( java.sql.Connection ) provides two transaction modes: autocommit and manual commit. java.sql.Connection provides the following methods for controlling transactions:

public void setAutoCommit(boolean)
public boolean getAutoCommit()
public void commit()
public void rollback()


    When using JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction. One disadvantage of JDBC transactions is that the scope of the transaction is limited to a database connection. A JDBC transaction cannot span multiple databases.

 

    2. JTA (Java Transaction API) transaction

    JTA is a high-level, implementation-independent, protocol-independent API that applications and application servers can use to access transactions.

    JTA allows applications to perform distributed transactions - accessing and updating data on two or more networked computer resources, which can be distributed across multiple databases. The JTA support of the JDBC driver greatly enhances data access capabilities.

    If you plan to use JTA to delimit transactions, you will need a JDBC driver that implements the javax.sql.XADataSource, javax.sql.XAConnection, and javax.sql.XAResource interfaces. A driver that implements these interfaces will be able to participate in JTA transactions. An XADataSource object is a factory for XAConnection objects. XAConnection s are JDBC connections that participate in JTA transactions.

    You will need to set up the XADataSource with the application server's administration tools. Instructions can be found in the application server and JDBC driver documentation.

     J2EE applications use JNDI to query data sources. Once the application finds the data source object, it calls javax.sql.DataSource.getConnection() to obtain a connection to the database.

    XA connections are different from non-XA connections. It is important to remember that XA connections participate in JTA transactions. This means that XA connections do not support JDBC's autocommit feature. Also, applications must not call java.sql.Connection.commit() or java.sql.Connection.rollback() on XA connections.

    Instead, applications should use UserTransaction.begin(), UserTransaction.commit() and serTransaction.rollback() .

 

    3. Container affairs

    The container transaction is mainly provided by the J2EE application server, and the container transaction is mostly completed based on JTA, which is a fairly complex API implementation based on JNDI. Relative coding to achieve JTA transaction management, we can complete the same function through the container transaction management mechanism (CMT) provided by the EJB container, which is provided by the J2EE application server. This allows us to simply specify which method to add to the transaction, and once specified, the container will take care of the transaction management tasks. This is our civil solution, because in this way we can exclude transaction code from logical coding, while leaving all the difficulties to the J2EE container to solve. Another benefit of using EJB CMT is that programmers don't need to care about coding the JTA API, however, in theory we have to use EJB.

    Four, three Java transaction differences

    1. The limitation of JDBC transaction control is within a database connection, but its use is simple.

    2. JTA transactions are powerful, transactions can span multiple databases or multiple DAOs, and the use is more complicated.

    3. Container transaction mainly refers to the transaction management provided by the J2EE application server, which is limited to the use of EJB applications.

    V. Summary

    Java transaction control is an indispensable part of building J2EE applications, and it is very important for the entire application system to choose which transaction to apply. Generally speaking, JDBC transaction can be selected in the case of a single JDBC connection connection. In the case of multiple connections or databases, JTA transaction needs to be selected. If EJB is used, EJB container transaction can be considered. 

 

Java JDBC transaction mechanism

 

  First of all, let's take a look at what major problems the existing JDBC operation will bring to us. For example, there is a business: when we modify a piece of information and then query the information, it seems that this is a simple business, and it is very easy to implement. , but when this business is placed on a multi-threaded and high-concurrency platform, problems naturally arise. For example, when we execute a modification, a thread also executes the modification statement before executing the query. This is when we execute the query again. The information we see may be different from what we modified. In order to solve this problem, we must introduce the JDBC transaction mechanism. In fact, the code implementation is very simple. Here is an example of the principle implementation for your reference:

private Connection conn = null;  

private PreparedStatement ps = null;  

try {  

 

    conn.setAutoCommit(false); //Set auto commit to false  

    ps.executeUpdate("Modify SQL"); //Execute the modification operation  

    ps.executeQuery("Query SQL"); //Execute query operation                 

    conn.commit(); //Manually commit after two operations are successful  

} catch (Exception e) {  

    conn.rollback(); //Once one of the operations fails, it will be rolled back, making both operations unsuccessful  

    e.printStackTrace ();  

  

JDBC's support for transactions is reflected in three aspects:

 

1. Auto-commit mode

Connection provides an auto-commit property to specify when the transaction ends .

a. When auto-commit is true, when the execution of each independent SQL operation is completed, the transaction is automatically committed immediately, that is to say, each SQL operation is a transaction.

When an independent SQL operation is completed, the JDBC specification stipulates this:

For data manipulation languages ​​(DML, such as insert, update, delete) and data definition languages ​​(such as create, drop), the execution of the statement is regarded as completed as soon as it is executed.

For a select statement, when the ResultSet object associated with it is closed, it is deemed to have completed its execution.

For stored procedures or other statements that return multiple results, when all ResultSet objects associated with it are closed, all update count (the number of rows affected by statement operations such as update, delete) and output parameter (the output parameters of the stored procedure) have been After the acquisition, it is deemed that the execution is completed.

b. When auto-commit is false, each transaction must explicitly call the commit method to commit, or explicitly call the rollback method to roll back. auto-commit defaults to true.

JDBC provides 5 different transaction isolation levels, which are defined in Connection.

 

2. Transaction Isolation Levels

JDBC defines five transaction isolation levels:

TRANSACTION_NONE JDBC driver does not support transactions

TRANSACTION_READ_UNCOMMITTED allows dirty reads, non-repeatable reads, and phantom reads.

TRANSACTION_READ_COMMITTED disables dirty reads, but allows non-repeatable and phantom reads.

TRANSACTION_REPEATABLE_READ prohibits dirty reads and non-repeatable reads, single-run phantom reads.

TRANSACTION_SERIALIZABLE Disables dirty reads, non-repeatable reads, and phantom reads.

  

  The higher the transaction isolation level, the more effort it takes to avoid conflicts. The Connection interface defines five levels, the lowest level specifying that transactions are not supported at all, and the highest level specifying that while a transaction is operating on a database, no other transaction must make any changes to the data that transaction is reading . In general, the higher the isolation level, the slower the application executes (due to increased resource consumption for locking and less concurrent operations among users). When deciding what isolation level to employ, developers must balance performance requirements and data consistency requirements.

  When a Connection object is created, its transaction isolation level depends on the driver, but is usually the default for the database involved. The user can change the transaction isolation level by calling the setIsolationLevel method. The new level will take effect for the remainder of the connection process. To change the transaction isolation level of only one transaction, it must be set before the transaction begins and reset after the transaction ends. We do not recommend making changes to the transaction isolation level in the middle of a transaction, as this will immediately trigger a call to the commit method, making any previous changes permanent. 
 

JDBC data isolation level settings:


 
         To solve the problem related to "multiple threads requesting the same data", transactions are separated from each other by locks. Most major databases support different types of locks; therefore, the JDBC API supports different types of transactions, which are assigned or determined by the Connection object. 
        The above levels appear in order to find a balance between performance and consistency. The higher the level of transaction protection, the greater the performance penalty.
        Assuming your database and JDBC driver support this feature, given a Connection object, you can explicitly set the desired transaction level:
        conn.setTransactionLevel(TRANSACTION_SERIALIZABLE) ;
        The level of the current transaction can be determined by:
            int level = conn.getTransactionIsolation();
            

 

3. Save Point

        JDBC defines the SavePoint interface, which provides a more fine-grained transaction control mechanism. When a savepoint is set, it is possible to rollback to the state at that savepoint instead of rolling back the entire transaction. The setSavepoint and releaseSavepoint methods of the Connection interface can set and release savepoints.

 

Although the JDBC specification defines the above supported behaviors of transactions, each JDBC driver and database vendor may have different degrees of support for transactions. If you set it arbitrarily in the program, you may not get the desired effect. To this end, JDBC provides the DatabaseMetaData interface, which provides a series of methods for obtaining the support of JDBC features. For example, the DatabaseMetaData.supportsTransactionIsolationLevel method can be used to determine the support for transaction isolation levels, and the DatabaseMetaData.supportsSavepoints method can be used to determine the support for savepoints.

Source: http://blog.csdn.net/yuejingjiahong/article/details/6663577

 http://blog.csdn.net/applehoney/article/details/2270732

http://lvwenwen.iteye.com/blog/2045951

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325220152&siteId=291194637