Java transaction and simple application example _java

Source: Internet
Author: User
Tags rollback

Simple use of Java transactions

Java transactions are asked in some interviews.

In the interview, the first thing we should answer is: The transaction can ensure the integrity and consistency of the data.

If you have a deep sense of skill: say some of the principles (before the task begins to set the uncommitted task, after all tasks are completed before submitting the task,
If the task is disconnected in the middle, perform a rollback, undo the task performed earlier, and simply cite an example (such as a question of saving money and getting paid).
For example: the bank transfers between two accounts, from a account into the B account 1000 yuan, the system first reduce a account of 1000 yuan, and then for B account increase of 1000 yuan. If all execution succeeds, the database is in consistency, and if only the changes to the a account amount are performed without increasing the amount of the B account, the database is in an inconsistent state, and the preceding action needs to be canceled. )

This article makes a simple discussion of Java transactions, and we need to know that this is related to the database.

A Let's look at a simple piece of code

Transaction processing using JDBC method

public int Delete (int sID) { 
  //the class
  databaseconnection DBC = new DatabaseConnection () that implements the database connection; 
  Get Connection object
  Connection con = dbc.getconnection (); 
  try { 
    con.setautocommit (false);//Change the default commit method for a JDBC transaction 
    dbc.executeupdate ("Delete from Xiao where id=" + SID); 
    Dbc.executeupdate ("Delete from xiao_content where id=" + SID); 
    Dbc.executeupdate ("Delete from Xiao_affix where bylawid=" + SID); 
    Con.commit ()//Submit JDBC Transaction 
    Con.setautocommit (TRUE);//restore default submission for JDBC Transactions 
    dbc.close (); 
    return 1; 
  } 
  catch (Exception exc) { 
    con.rollback ();//rollback JDBC Transaction 
    dbc.close (); 
    return-1; 
  } 

The above piece of code is a simpler implementation of Java transactions.
The above three times the deletion operation, as long as one execution failed, will perform the task rollback, the equivalent of either success, or nothing.

If there is no management of the transaction, the previous execution will be updated immediately in the database,
When execution fails, the task is no longer performed, and the data is not guaranteed to be consistent.

Two Basic concepts of Java transactions

atomicity (atomicity): A transaction is a complete operation. The steps of a transaction are not separate (atomic);
Either executed or not executed.
Consistency (consistency): When a transaction completes, the data must be in a consistent state
Isolation (Isolation): All concurrent transactions that modify data are isolated from each other, indicating that the transaction must be independent,

It should not rely on or affect other transactions in any way
Permanent (durability): When a transaction is completed, its modifications to the database are persisted, and the transaction log keeps the transaction permanent

Java Transaction Description: If you do multiple operations on a database, each execution or step is a transaction.
If the database operation fails at a certain step or causes a transaction to fail, then some of the transactions are executed and are not executed.
So that there is a rollback of the transaction, cancel the previous operation ....

In database operations, a transaction is an indivisible unit of work that consists of one or more SQL statements that are updated on the database.
The entire transaction can be committed to the database only if all operations in the transaction are completed properly, and if one of the operations is not completed,
You must undo the entire transaction.

For example, in a bank transfer transaction, assume that John from his account to transfer 1000 yuan to the Dick account, the relevant SQL statements are as follows:

Update account set monery=monery-1000 where name= ' Zhangsan '

Update account set monery=monery+1000 where Name= ' Lisi '

This two statement must be handled as a completed transaction. This transaction can only be committed if both are executed successfully.
If one sentence fails, the entire transaction must be undone.

3 methods of controlling transactions are provided in the connection class:
(1) setautocommit (Boolean autocommit): Set whether the transaction is automatically submitted;
(2) commit (); commit the transaction;
(3) rollback (), cancellation of business;

In the JDBC API, the default scenario is autocommit transactions, that is, each updated SQL statement for the database represents a transaction.
When the operation succeeds, the system automatically invokes commit () to commit, or the rollback () is invoked to undo the transaction.

In the JDBC API, you can suppress autocommit transactions by calling Setautocommit (false).
You can then make a multiple update database SQL statement as a transaction, after all operations are completed, invoke commit () to commit the whole.
If one of the SQL operations fails, the commit () method is not executed, but the corresponding SqlException is generated.
You can then capture the exception code block by invoking the rollback () method to undo the transaction.

In general, developers who specialize in database development must be very knowledgeable about the business,
But the average programmer doesn't have to spend too much time on this. There is a general understanding of the role.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.