Javawebday47 (transaction, four core features isolation level __javaweb

Source: Internet
Author: User
Tags rollback
Four characteristics of transaction transaction ACID MySQL operation transaction in JDBC operation transaction Transaction Overview 1, what is transaction bank transfer. John turn 1000 to Dick. Requires two SQL statements to the John account minus 1000 yuan to Dick's account plus 1000 yuan if the first SQL statement succeeds, the program is interrupted (possibly by throwing an exception or some other reason) before executing the second SQL statement dick Without adding, John is definitely not going to work. Multiple operations in a transaction that are either completely successful or fail completely, and cannot exist half the case 2, the four characteristics of the transaction (ACID) atomicity (atomicity) All operations in the transaction are non-delimited atomic units. The database state is consistent with other business rules after all the operations in the transaction are either all successful or all failed consistency (consistency) transactions are performed. such as transfer business, regardless of the success of the implementation of the transaction, the sum of the two account balances involved in the transfer should be the same as the "most important feature, others serve it." Isolation (isolation) isolation means that in concurrent operations, different transactions should be isolated directly, so that each concurrent transaction does not interfere with the persistence of each other (D urability) Once the transaction is committed successfully, all data operations in the transaction must be persisted to the database, even if the transaction is committed, the database crashes immediately, and after the database is restarted, it must be guaranteed to recover data by some mechanism 3, the transaction in MySQL by default, MySQL is a separate transaction for each execution of a SQL statement. If you need to include more than one SQL statement in a transaction, you need to open the transaction and end the transaction open the transaction Start transaction end transaction Commit or rollback execute the start TRA before executing the SQL statement Nsaction This opens a transaction (the starting point of the transaction) and then executes multiple SQL statements, and finally ends the transaction, committing the commit, which means that the impact of multiple SQL statement locks in the transaction is persisted to the database. Or rollback represents a rollback, that is, rolling back to the start of a transaction, all previous operations were undone the JDBC transaction handles transactions in JDBC, all operations in the same transaction through connection, using the same Connection object 1, Three methods of transaction connection in JDBC are related to transaction SetautocommIt (Boolean); Set whether the transaction is automatically committed, if True (the default is True) for autocommit, that is, each executed SQL statement is a separate transaction, and if set to false, it is the equivalent of opening a transaction; Conn.setautocommit ( False) to open a transaction commit (), commit an end transaction, Conn.commit () to commit a transaction rollback (): Rollback END transaction. Conn.rollback () indicates that the code format for Transaction JDBC processing transaction try{Conn.setautocommit (FALSE),//Open transaction ... conn.commit ( //try last COMMIT Transaction} catch () {conn.rollback ();/ROLLBACK TRANSACTION} Transaction ISOLATION Level 1, transaction concurrent read problem dirty read: Read to another transaction uncommitted data (cannot be allowed to appear) Things) cannot be read repeatedly: Two read inconsistent Phantom read (virtual Read): Read to another transaction committed data 2, concurrent transaction problem because concurrent transactions cause problems with roughly 5 classes, two of which are update problems, three are read problem dirty read (dirty read) READ UNCOMMITTED New data, that is, read dirty data not repeatable read (unrepeatable read) inconsistent two reads for the same record, because another transaction made a modification to the record The Phantom Read (Phantom Read) is inconsistent with the two queries on the same table because another transaction inserts into a record dirty read transaction 1: John to Dick transfer 100 Yuan transaction 2: Dick View own account T1: Transaction 1: Start transaction t2: Transaction 1: John Transfer to Dick 100 source T3: Transaction 2 : Start a transaction T4: Transaction 2: Dick view their account, see the account out of 100 yuan (dirty Read) T5: Transaction 2: Commit TRANSACTION T6: Transaction 1: ROLLBACK TRANSACTION, back to the state of transfer Transaction 1: Hotel Check Two times, room 1024th, Status 2: Book Room 1024th. T1: Transaction 1: Start transaction t2: Transaction 1: View 10Room 24th is free T3: Transaction 2: Start transaction T4: Transaction 2: Encounter 1024th Room T5: Transaction 2: Commit TRANSACTION T6: Transaction 1: View room 1024th again for use T7: Transaction 1 : Inconsistent two query results for the same record committed by a transaction Phantom transaction 1: Two statistics for hotel room Reservations 2: Add a reservation record T1: Transaction 1: Start transaction T2: Things Service 1: Statistics booking record 10 T3: Transaction 2: Start transaction T4: Transaction 2: Add a Reservation record T5: Transaction 2: Commit TRANSACTION T6: Transaction 1: Statistics booking record is 11 T7: Transaction 1: Commit a transaction inconsistent with two queries on the same table the difference between non-repeatable read and Phantom Read is read to another transaction's update Phantom read is read to another transaction insert (in MySQL can not test to phantom read) 3, four isolation levels 4, etc. Level of transaction isolation, in the same data environment, using the same input, performing the same work, according to different isolation levels, can lead to different results.
        The ability to resolve data concurrency problems at different transaction isolation levels is different 1, SERIALIZABLE (serialized) Three kinds of read problems can be resolved without any concurrency problems, because it is the same data access is serial, not concurrent access. Worst performance 2, Repeatable READ (repeatable) (MySQL) dirty read, not repeatable read, unable to handle phantom read to prevent dirty read and not repeatable read performance than serializable good 3, Read Committed (Read the submitted data)
        (Oracle locates the default isolation level) can only handle dirty reads, cannot handle unreadable and phantom reads prevent dirty read performance than repeatable read 4, READ UNCOMMITTED (READ UNCOMMITTED data) nothing. There may be any transactional concurrency problem performance best 5, MySQL isolation level MySQL's default isolation level is REPEATABLE READ SELECT @ @tx_iSolation view You can also set the isolation level for the current connection by using the following statement sets transaction IsolationLevel [4 Select 1] 6, JDBC settings isolation level Con.settransactionisolati
        The optional value for the on (int level) parameter is as follows connection.transaction_read_uncommitted connection.transaction_read_committed
        Connection.transaction_repeatable_read connection.transaction_serializable Transaction Summary transaction characteristics: ACID Transaction start and end boundaries: Start Boundary (Con.setautocommit (false)), End boundary (Con.commit () or Con.rollback ()) Transaction ISOLATION level: Read_umcommitted, read_com
 Mitted, Repeatable_read, SERIALIZABLE Multiple transactions concurrent execution requires consideration of concurrent transactions
public class Accountdao {/** * Modify the balance of the specified user * @param name * @param balance */public void UpdateBalance (Connection con,string name,double balance) {try{* * 1, Get the Connection Object * * * 2, give the SQL template, create pstmt/String sql = "Update ac Count Set balance=balance+? where Name=?
            ";
            PreparedStatement pstmt = con.preparestatement (sql);
            * * 3, to the parameters of the assigned value * * pstmt.setdouble (1, balance);
            Pstmt.setstring (2, name);
        * * 4, the implementation of */pstmt.executeupdate ();
        }catch (Exception e) {throw new RuntimeException (); }
    }
}
/** * Demo Transfer * All operations on the connection are processed at the service level. * To deal with this problem, hide all the connection operations.
    Need to use a custom gadget/public class Demo1 {/** * Transfer method * @param form * @param to * @param money * * public void Zhuanzhang (String from,string to,double) {//operation of transaction must use Connection object Connection con =
        Null
            try{//Open transaction con = jdbcutils.getconnection ();


            Con.setautocommit (FALSE);
            Accountdao dao = new Accountdao (); Dao.updatebalance (Con,from,-money)//minus the corresponding amount to form if (true) {throw new RuntimeException ("Transfer failed")
            ;
        Dao.updatebalance (Con,to, Money)//To add the corresponding amount//to the transaction con.commit ();
                catch (Exception e) {//ROLLBACK TRANSACTION try {con.rollback ();
            Con.close ();
        The catch (SQLException E1) {} throw new RuntimeException (e);
 }} @Test   public void Fun1 () {Zhuanzhang ("Zs", "ls", 100);
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.