Java transaction-local transaction, java transaction

Source: Internet
Author: User

Java transaction-local transaction, java transaction
Local transactionTransaction type

Transactions can be divided into local transactions and distributed transactions. These two transaction types are distinguished based on the amount of data resources accessed and updated. Local transactions access and update data on a single data source, while distributed transactions access and update data across multiple data sources. Here we will talk about transactions based on data sources such as databases.

JDBC transactions

In JAVA, we use JDBC to connect to the database, access and update data. In JDBC, how is the transaction implemented? Who manages the transaction? The answer is of course the database. JDBC itself does not have the ability to process transactions, but relies on the underlying database to provide transaction services. As mentioned in many documents, JDBC transactions are Connection-based, that is, the Connection object. The essence of this Connection is actually a Socket connected to the database, after establishing a connection with the database, you can send commands and data to the database. In the end, the database adds, deletes, modifies, queries, and processes transactions based on the received commands and data. In addition, the transaction is restricted on a single connection, which is like we go to the bank's business office to handle the business, the business office has multiple windows, we will only communicate with bank staff in our own window and process our own business, rather than cross-window, tell the staff in other windows to transfer the money from the buddy to his card.

 

Database Transaction example

 

The following is an example of a MYSQL database transaction:

 

1. Create a table

Create user table

Create table users (USER_ID int not null AUTO_INCREMENT COMMENT 'Auto increment primary key', USER_NAME VARCHAR (25) not null comment 'username', password varchar (25) not null comment 'Password ', gender varchar (1) COMMENT 'gender', PHONE_NO VARCHAR (11) not null comment 'mobile phone number', CREATE_TIME datetime not null default CURRENT_TIMESTAMP () COMMENT 'creation time ', primary key (USER_ID) COMMENT = 'user table ';

Create a user-role Association Table

Create table USER_ROLE_RELATION (REL_ID int not null AUTO_INCREMENT COMMENT 'auto-incrementing primary key', USER_ID int not null comment 'user id', ROLE_ID int not null comment 'Role id ', primary key (REL_ID) COMMENT = 'user-role ing table'

2. Create a stored procedure and use transactions in the Stored Procedure

BEGIN # DECLARE a flag. The DEFAULT value is 0 DECLARE T_ERROR integer default 0; # If an exception occurs during transaction execution, SET the flag to 1 declare continue handler for sqlexception set T_ERROR = 1; # start transaction;
Insert into users (USER_NAME, PASSWORD, GENDER, PHONE_NO) VALUES ('hangsan', '000000', 'mal', '000000'); insert into USER_ROLE_RELATION (USER_ID, ROLE_ID) VALUES ('20140901', '1'); # IF the execution is successful, submit it directly; otherwise, roll back IF T_ERROR = 0 then commit; else rollback; end if; END

3. Execute the Stored Procedure

After the stored procedure is successfully executed, one record will appear in the two tables of the database. Then

INSERT INTO USER_ROLE_RELATION (USER_ID, ROLE_ID) VALUES ('333', '1');

This statement is changed:

# This INSERT statement violates non-NULL constraints and throws an exception insert into USER_ROLE_RELATION (USER_ID, ROLE_ID) VALUES (NULL, '1 ');

Save and execute the stored procedure again. The result is that no records are added in both tables. The two SQL statements either succeed or fail at the same time.

 

JDBC transaction example

 

If you need to manually submit a transaction in JDBC, you need to use three methods in the Connection object:

 

// Set whether to automatically submit setAutoCommit () // submit commit () // roll back rollback ()

 

In JDBC, the transaction commit method is automatically submitted by default. If you manually submit a transaction, you need to change the default settings:

 

Connection.setAutoCommit(false)

 

The following example shows how to add a new user and assign the default permissions to the user. You need to insert a record into the two tables at the same time, and regard the new user and permissions as an execution unit, in a transaction.

Package person. lb. jdbc; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; public class TestJDBCTransAction {static {try {// load the driver Class. forName ("com. mysql. jdbc. driver ");} catch (ClassNotFoundException e) {e. printStackTrace () ;}} public static void main (String [] args) {// executeTransaction ();} private Static void executeTransaction () {Connection conn = null; Statement st1 = null; Statement st2 = null; ResultSet rs = null; try {// get database Connection conn = (Connection) DriverManager. getConnection ("jdbc: mysql: // 192.168.0.105: 3306/TEST", "root", "root"); conn. setAutoCommit (false); st1 = (Statement) conn. createStatement (); st2 = (Statement) conn. createStatement (); // INSERT user information st1.execute ("insert into users (US ER_NAME, PASSWORD, GENDER, PHONE_NO) "+" VALUES ('hangsan', '000000', 'mal', '000000') ", Statement. RETURN_GENERATED_KEYS); // obtain the new rs = st1.getGeneratedKeys (); String userID = ""; if (rs. next () {userID = rs. getString (1);} // INSERT the user and role associated data st2.execute ("insert into USER_ROLE_RELATION (USER_ID, ROLE_ID) VALUES (" + userID + ", '1 ')"); conn. commit ();} catch (SQLException e) {e. printStackTrace (); Try {conn. rollback ();} catch (SQLException e1) {e1.printStackTrace () ;}} finally {try {if (rs! = Null) {rs. close () ;}if (st1! = Null) {st1.close () ;}if (st2! = Null) {st2.close () ;}if (conn! = Null) {conn. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}}

The program execution result is as follows:

USERS table

USER_ROLE_RELATION table

 

 

At this point, the JAVA local transaction is finished.

 

 

 

 

 

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.