Local transactiontransaction type
Transactions can be divided into two types of local transactions and distributed transactions. The two types of transactions are differentiated based on how much data resources are accessed and updated. Local transactions are access to and updates to data on a single data source, and distributed transactions are data access and updates across multiple data sources. The transaction to be said here is based on the data source of the database.
JDBC Transaction
In JAVA , we use JDBC to connect to databases, access and update data. So How do you implement transactions in JDBC, and who manages the transactions? This answer is of course the database,JDBC itself does not have the ability to handle transactions, but relies on the underlying database, the underlying database to provide transactional services. It is mentioned in many data thatthe JDBC transaction is based on the connection, that is, the Connection object, which is actually connected to a database Socket , a connection to the database can be sent to the database to send instructions and data, the final database will be based on the received instructions and data for the pruning and processing of transactions. In addition, the transaction is limited to a single connection, it is like we go to the bank's business hall, there are several windows, we will only in their own window with the bank staff to communicate and handle their own business, but not across the window, tell other windows of the staff to the man's money to his card, That's all I can think about.
Database Transaction Example
Let's look at a MYSQL Database Transaction Example:
1. Create a table
Create a user table
CREATE TABLEUSERS (user_id INT not NULLAuto_increment COMMENT'self-increment primary key', user_name VARCHAR( -) not NULLCOMMENT'User name', PASSWORDVARCHAR( -) not NULLCOMMENT'Password', GENDERVARCHAR(1) COMMENT'Sex', Phone_noVARCHAR( One) not NULLCOMMENT'Phone number', Create_timeDATETIME not NULL DEFAULT Current_timestamp() COMMENT'creation Time', PRIMARY KEY(user_id)) COMMENT= 'User Table';
Create an association relationship table for users and roles
CREATE TABLEuser_role_relation (rel_idINT not NULLAuto_increment COMMENT'self-increment primary key', user_id INT not NULLCOMMENT'User ID', role_idINT not NULLCOMMENT'role ID', PRIMARY KEY(rel_id)) COMMENT= 'User and Role correspondence table'
2. Create stored procedures to use transactions in stored procedures
BEGIN#声明一个标志位, default is 0DECLARET_errorINTEGER DEFAULT 0; #如果事务执行过程中出现异常, set the flag bit to 1DECLARE CONTINUEHANDLER forSQLEXCEPTIONSETT_error= 1; #开始事务 STARTTRANSACTION;
INSERT intoUSERS (user_name, PASSWORD, GENDER, Phone_no)VALUES('Zhangsan','123456','male','11111111111'); INSERT intoUser_role_relation (user_id, role_id)VALUES('333','1'); #如果执行成功, submit directly, otherwise roll backIFT_error= 0 Then COMMIT; ELSE ROLLBACK; END IF; END
3. Execute Stored Procedure
After the stored procedure executes successfully, a record appears in both tables of the database. Then put
INSERT into User_role_relation (user_idVALUES ('333'1') );
This statement should read:
#这条INSERT语句违反了非空约束, an exception is thrown INSERT into User_role_relation (user_idVALUES (NULL'1');
The stored procedure is re-saved and executed with the result that there are no new records in the two tables. Two SQL statements either succeed at the same time or fail at the same time.
JDBC Transaction Example
in JDBC, if you need to commit a transaction manually, you need to use the three methods in the Connection object:
// set whether to submit automatically Setautocommit () // Submit commit () // Roll Back rollback ()
The way in which transactions are submitted in JDBC is automatically committed by default, and the default settings are changed if you manually commit a transaction:
Connection.setautocommit (false)
The following example assumes that a new user is added and assigns default permissions to the user, so you need to insert a single record into each of the two tables, adding the new user and assigning permissions as an execution unit and placing them in a single transaction.
PackagePerson.lb.jdbc;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classtestjdbctransaction {Static { Try { //Load Driver classClass.forName ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {//Execution Transactionsexecutetransaction (); } Private Static voidexecutetransaction () {Connection conn=NULL; Statement St1=NULL; Statement St2=NULL; ResultSet RS=NULL; Try { //Get database connectionconn =(Connection) drivermanager.getconnection ("Jdbc:mysql://192.168.0.105:3306/test", "Root", "Root"); Conn.setautocommit (false); St1=(Statement) conn.createstatement (); St2=(Statement) conn.createstatement (); //Inserting user InformationSt1.execute ("INSERT into USERS" (user_name, PASSWORD, GENDER, phone_no) "+" VALUES (' Zhangsan ', ' 1234 56 ', ' Male ', ' 11111111111 ') ", Statement.return_generated_keys); //gets the new value of the growth columnrs =St1.getgeneratedkeys (); String UserID= ""; if(Rs.next ()) {UserID= rs.getstring (1); } //Insert user and Role Association dataSt2.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 blockE.printstacktrace (); } } }}
The results of the program execution are as follows:
USERS Table
User_role_relation Table
Here,JAVA 's local business is finished.
Java Transactions-Local transactions