Simple use of Java transactions
Java affairs will be asked during some interviews.
During the interview, the first thing we need to answer is: transactions can ensure the integrity and consistency of data.
If the skills are deeper: just talk about some principles (set not submit tasks before the task starts, and submit tasks after all tasks are completed.
If the task is disconnected in the middle, rollback will be performed and the previous task will be cancelled), and a simple example will be given (such as the issue of saving and withdrawing money.
For example: the bank transfers money between two accounts, transfers from Account A to Account B for 1,000 yuan. The system first reduces Account A by 1,000 yuan, and then adds 1,000 yuan to Account B. If all executions are successful, the database is in consistency; if only the modification of the amount of Account A is completed without increasing the amount of Account B, the database is in an inconsistent state, and the previous operation needs to be cancelled. )
This article briefly discusses Java transactions. When we ask about Java transactions, we need to know that this is related to databases.
one. Let's look at a simple code first
Use JDBC to perform transaction processing
public int delete(int sID) { //Class that implement database connection DataBaseConnection dbc = new DataBaseConnection(); //Get the connection object Connection con = dbc.getConnection(); try { con.setAutoCommit(false);//Change the default commit method of JDBC transactions 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();//Commit JDBC transaction con.setAutoCommit(true);//Restore the default commit method of JDBC transaction dbc.close(); return 1; } catch (Exception exc) { con.rollBack();//Rolle back JDBC transaction dbc.close(); return -1; } } The above code is a simple execution of a Java transaction.
The above three times of deletion operations are performed. As long as one fails, the task will be rolled back, which is equivalent to either success together or nothing is done.
If there is no transaction management, the previous execution will be updated in the database immediately.
Exit the subsequent tasks wherever the execution fails, and the consistency of the data cannot be guaranteed.
two. The basic concept of Java transactions
Atomicity: A transaction is a complete operation. The operations of the transaction are inseparable (atomic);
Either execute them or none of them
Consistency: When a transaction completes, the data must be in a consistent state.
Isolation: All concurrent transactions that modify data are isolated from each other, which means that the transaction must be independent.
It should not depend on or affect other transactions in any way (Durability): After a transaction is completed, its modifications to the database are permanently maintained, and the transaction log can maintain the transaction's permanentness.
Java transaction processing description: If you perform multiple operations on the database, each execution or step is a transaction.
If the database operation is not executed at a certain step or an exception occurs, resulting in the transaction failure, so some transactions are executed and some are not executed.
This leads to transaction rollback and cancels previous operations...
In a database operation, a transaction refers to an inseparable unit of work composed of one or more SQL statements that update the database.
Only when all operations in the transaction are completed normally can the entire transaction be submitted to the database. If an operation is not completed,
The entire transaction must be revoked.
For example, in bank transfer transactions, suppose that Zhang San transfers 1,000 yuan from his account to Li Si's account, the relevant SQL statements are as follows:
update account set money=monery-1000 where name='zhangsan'
update account set money=monery+1000 where name='lisi'
These two statements must be processed as a completed transaction. This transaction can only be submitted when both are successfully executed.
If one sentence fails, the entire transaction must be revoked.
There are 3 methods to control transactions in the connection class:
(1) setAutoCommit(Boolean autoCommit): Set whether to automatically submit transactions;
(2) commit(); commit(); commit transaction;
(3) rollback(); undo the transaction;
In the jdbc API, the default case is to automatically commit transactions, that is, each update to the database represents a transaction.
After the operation is successful, the system automatically calls commit() to commit, otherwise rollback() will be called to undo the transaction.
In the jdbc API, automatic transaction submission can be prohibited by calling setAutoCommit(false).
Then you can use multiple SQL statements that update the database as a transaction. After all operations are completed, commit() is called to make the overall submission.
If one of the sql operations fails, the commit() method will not be executed, but the corresponding sqlException will be generated.
At this time, you can catch the exception in the code block, call the rollback() method to undo the transaction.
Generally speaking, developers who specialize in developing databases must have a deep understanding of transactions.
But the average programmer doesn't need to spend much time on this. Just have an understanding of the general effect.
Thank you for reading, I hope it can help you. Thank you for your support for this site!