There are two main aspects:
One is to start a business
Conn.setautocommit (false); default is True
The second is to commit the transaction
Conn.commit ();
First, create a class
The method of connecting to the database is encapsulated in the Util package and gets the connection connection. The function of this class is to modify the value of the acount of the corresponding ID in the table t_emp by ID.
Use the connection Preparestatement method.
Public classAcountdao { Public voidUpdate (Connection conn,integer Id,integer count) {String SQL= "Update t_emp set acount=acount+?" where id=? "; PreparedStatement PS=NULL; Try{PS=conn.preparestatement (SQL); Ps.setint (1, Count); Ps.setint (2, id); Ps.executeupdate (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Second, create a test class JUnit test case
PrivateAcountdao acountdao=NewAcountdao (); @Test Public voidtestupdate () {Connection conn=NULL;//A Connection object conn=Util.getconn (); Try {//open Transaction, manual commit requiredConn.setautocommit (false);
Monkey King to pig transfer 100 Yuan Acountdao.update (conn,1,-100);//A Connection objectintaa=10/0;
Pig received a transfer from the Monkey King of 100 Yuan Acountdao.update (conn,2, 100);//A Connection object//Commit a transactionConn.commit (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { Try{conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
Here we need to Note : we
Acountdao.update (); There are connection in the method, plus the connection object that the program just started to create, with a total of 3 connection objects. We're going to keep 3 of them.
The connection object is the same connection object.
When the Monkey King has made an error after the transfer, the method of committing the transaction can be rolled back, the operation that is about to be executed rolls back, rolls back to the moment when the transaction was started, which is equivalent to never executed.
Spring Transaction Processing