JAVA Transaction Personal Notes

Reference Blog: https://www.jianshu.com/p/603b52d2ae4b

  1. Basic knowledge.
    Transaction is a concept at the database level that guarantees uniqueness for every operation on the database. It either succeeds or fails. Specifically, take a more general example:
    Person A transfers 10,000 yuan to Person B. This trigger will result in 10,000 yuan less in A's bank account and 10,000 yuan more in B's bank account. But in case of emergency, when A's $10,000 was deducted, the network was interrupted or the system crashed, B did not increase this $10,000, but A's $10,000 actually disappeared.
    This example is obviously a failed business case, which should be accompanied by transaction control, that is, the business must complete all processes at once and succeed, or the business will fail, be undone, and return to the state before execution to protect the security of the data!
    (Although it has nothing to do with database-level transactions, I deleted one attribute of table and added another attribute to a flyway script before I started flyway, but the SQL that I added the attribute to was written incorrectly, flyway will fail when it finishes executing and the script will fail. However, the first deletion statement is executed, so it is Even if the script is correctly changed in history, execution will error that the attribute to be deleted cannot be found! So flyway writes scripts, deleting and adding fields should be isolated, referencing transaction isolation!)

Transactions have four characteristics (ACID):
- atomicity: Atomicity
Transactions are the most basic logical unit of a database, and they either execute successfully or not at all. Individuals believe that understanding this concept is most important for understanding transactions.
- consistency: consistency
When a transaction is completed, all data must be consistent. In a database, all rules must be applied to transaction modifications to ensure data integrity. (A less than 10,000, B more than 10,000, the total remains unchanged)
- isolation: isolation
Execution of one transaction cannot be affected by other transactions
- durability: persistence
Transactions remain in the DB permanently after they are committed, and the operations associated with committing transactions are not lost even in the event of unexpected events.

  1. java transactions
    Java has three types of transactions: jdbc transactions, jta transactions (java transaction api), and container transactions.
    JDBC transactions:
    Operation flow:
    1) Get JDBC connection ->2) Declare SQL ->3) Pre-compile SQL ->4) Execute SQL ->5) Process result set ->
    6) Release Result Set->7) Release Statement->8) Submit Transaction->9) Handle Exceptions and Roll Back Transaction->10) Release JDBC Connection
    Advantages and disadvantages of JDBC: 1. Long, repetitive 2. Display transaction control 3. Not available for each step 4. Display handling checked exceptions
    5. Multiple databases are not operational

  2. Spring Container Transactions
    Spring does not directly manage transactions, but rather provides a variety of transaction managers that delegate their transaction management responsibilities to transactions within the relevant platform framework provided by persistence mechanisms such as Hibernate or JTA. The interface of the Spring Transaction Manager is org.springframework.transaction.PlatformTransaction Manager. Through this interface, Spring provides transaction managers for various platforms such as JDBC, Hibernate, etc., but the specific implementation is their own thing.
    Either call the commit() method or the rollback() method.

Public interface PlatformTransactionManager{  
      // Getting the TransactionStatus object from TransactionDefinition
      TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;
    // Submit
      Void commit(TransactionStatus status) throws TransactionException;  
      // RollBACK
      Void rollback(TransactionStatus status) throws TransactionException;  
}

Get the transaction object through getTransaction, passed in as TransactionDefinition, which defines some basic transaction properties. According to this blog post, transaction attributes are some of the basic configurations of transactions, describing how transaction policies refer to methods.
Transaction properties include five aspects:
- Propagation behavior, isolation rules, rollback transactions, transaction timeout, read-only or not.
TransactionDefinition:
public interface TransactionDefinition {
int getPropagationBehavior(); // Return the propagation behavior of the transaction
int getIsolationLevel(); // Returns the isolation level of a transaction against which the transaction manager controls which data within the transaction can be seen by another transaction
int getTimeout(); // How many seconds must the return transaction complete
boolean isReadOnly(); // Whether the transaction is read-only or not, the transaction manager can optimize based on this return value to ensure that the transaction is read-only
}

- PROPOGATION There are seven types of dissemination:
· PROPAGATION_REQUIRED: If there is currently no transaction, create a new one and join it if one already exists. This is the most common choice.
· PROPAGATION_SUPPORTS: Supports the current transaction and executes non-transactionally if no transaction exists.
· PROPAGATION_MANDATORY: Supports the current transaction and throws an exception if no transaction exists.
· PROPAGATION_REQUIRES_NEW: Create a new transaction and suspend it if one exists.
· PROPAGATION_NOT_SUPPORTED: Perform the operation non-transactionally and suspend the current transaction if one exists.
· PROPAGATION_NEVER: Executes non-transactionally and throws an exception if a transaction currently exists. 
There are seven, but the first is the most common. REQUIRED And the fourth REQUIRES_NEW. 

- ISOLATION There are five levels of isolation for transactions:
ISOLATION_DEFAULT: This is a PlatfromTransactionManager Default isolation level, using the database default transaction isolation level.
The other four and JDBC Corresponding isolation level;
ISOLATION_READ_UNCOMMITTED: This is the lowest isolation level for a transaction, allowing another transaction to see uncommitted data for that transaction.
This isolation level results in dirty, non-repeatable and phantom reads.
ISOLATION_READ_COMMITTED: Ensure that data modified by one transaction is committed before it can be read by another transaction. Another transaction cannot read uncommitted data from the transaction.
This level of transaction isolation prevents dirty reads, but non-repeatable and phantom reads may occur.
ISOLATION_REPEATABLE_READ: This level of transaction isolation prevents dirty reads from being repeated. However, phantom reading may occur.
In addition to guaranteeing that one transaction cannot read uncommitted data from another, it also guarantees that the following situations are avoided(Non-repeatable reading). 
**ISOLATION_SERIALIZABLE**: This is the most expensive but reliable level of transaction isolation. Transactions are processed for sequential execution.
In addition to preventing dirty reading and non-repeatable reading, phantom reading is also avoided.

- The properties of a transaction can be configured as annotated or as a profile:
@Transactional: 
@Transactional Can only be applied to public Methodologically,For other non public Method,If marked@Transactional No error,However, the method does not have transaction capability.(A key!!!)
By default,A Transactional Method, encounter RuntimeException Will roll back . The checked exception is not rolled back. To roll back all exceptions,To add @Transactional( rollbackFor={Exception.class,Other Exceptions}) 
@Transactional(
	    readOnly = false, //Read-Write Transactions
	    timeout = -1 ,     //Transaction timeout, -1 is unlimited
	    noRollbackFor = ArithmeticException.class, //Do not roll back on specified exception
	    isolation = Isolation.DEFAULT, //Transaction isolation level, where the default isolation level for back-end databases is used
	    propagation = Propagation.REQUIRED //Propagation behavior of transactions
	)

The following is an example of adding transactions in SpringBoot:
This is a class management mode. When deleting a class, the class is deleted first, then the class information of the students is set to null, and the grouping status is set to not grouped.
When deleting a class, an exception is thrown if there is a problem setting the properties of the student object, but at that time, although an exception is thrown, the class has been deleted and there is no information about the class in the database. So open the transaction so that the whole process either succeeds or fails. At this time, if any problems occur after the class is deleted, the status before submission will be withdrawn.

@Transactional(rollbackFor=Exception.class)
    public void deleteClassById(Long classId) {
        ClassInfoDo classInfoDo = classDomainService.findClassById(classId);
        List<StudentInfoDo> studentInfoDos = studentDomainService.findAll().stream()
                .filter(item -> Objects.equals(item.getClassId(), classInfoDo.getClassId()))
                .collect(Collectors.toList());
        List<TeacherInfoDo> teacherInfoDos = teacherDomainService.findAll().stream()
                .filter(item -> Objects.equals(item.getClassId(), classInfoDo.getClassId()))
                .collect(Collectors.toList());
        classDomainService.deleteClassById(classId);
        studentInfoDos.stream()
                .peek(StudentInfoDo::setPropertiesToNull)
                .collect(Collectors.toList());
        teacherInfoDos.stream()
                .peek(TeacherInfoDo::setPropertiesToNull)
                .collect(Collectors.toList());
        studentDomainService.saveAll(studentInfoDos);
        teacherDomainService.saveAll(teacherInfoDos);
    }

Keywords: Java Back-end

Added by Control Pad on Mon, 22 Nov 2021 07:29:50 +0200