Biography: Swing unruly, love life. Java Cultivator (wechat official ID: Java Cultivator), welcome to follow. Access to 2000G of detailed information on the 2020 interview questions

Definition of ** transaction: ** transaction refers to a collection of multiple units of operation. The operations of multiple units are indivisible as a whole, and either none of them succeed or all of them succeed. It must follow four principles (ACID).

  • Atomicity: a transaction is the smallest indivisible unit of work in which all or none of the operations are performed.

  • Consistency: The data of the database is in the correct state before the transaction is executed, but the data of the database is still in the correct state after the transaction is executed, that is, the data integrity constraint is not broken; If the bank transfers money from A to B, it must be guaranteed that the money from A must be transferred to B, and the money from A must not be transferred to B but not received by B, otherwise the data in the database will be in an inconsistent (incorrect) state.

  • Isolation: The execution of concurrent transactions does not affect each other. Operations within one transaction have no impact on other transactions. This requires the transaction Isolation level to specify the Isolation.

  • Durability: Once a transaction succeeds, its changes to database data must be permanent and do not cause data inconsistencies or loss due to, for example, system failures or power outages.

Spring provides two ways to manage transactions:

  • Declarative transaction management (transaction control based on configuration) : The bottom layer is based on Spring AOP, intercepting before and after mode execution, creating a new transaction or joining an existing transaction before the target method starts execution, and finally committing or rolling back the transaction after the target method completes execution, depending on the situation. The biggest advantage of declarative transactions is that no programming is required to take transaction management away from the complex business logic. It is simply configured in a configuration file and annotated with the @Transactional annotation on the target method.

  • Programmatic transaction management (based on Java programming to achieve transaction control), not recommended! : allows users to explicitly call beginTransaction() to start a transaction, commit() to commit a transaction, and rollback() to rollback a transaction in the implementation code, thus achieving a precise definition of transaction boundaries.

The transaction type commonly used by Spring (propagation property)**** defines seven constants representing propagation behavior in the TransactionDefinition interface:

  • PROPAGATION_REQUIRED: Supports the current transaction, or creates a new one if there are none. This is the most common choice and the default. (Use the @transactional annotation when using the @transactional method: @Transactional(Propagation =Propagation.REQUIRED, similar below)

  • PROPAGATION_SUPPORTS: Supports the current transaction, and executes non-transactionally if there is no transaction currently.

  • PROPAGATION_MANDATORY: Supports the current transaction, or throws an exception if there is no transaction

  • PROPAGATION_REQUIRES_NEW: Creates a transaction, and suspends the current one if it exists

  • PROPAGATION_NOT_SUPPORTED: Executes an operation in a non-transactional manner, and suspends the current transaction, if one exists.

  • PROPAGATION_NEVER: Executes non-transactionally, throws an exception if a transaction currently exists

  • PROPAGATION_NESTED: Executes within a nested transaction if a transaction currently exists. If there are no transactions currently, do something similar to REQUIRED. With multiple savepoints that can be rolled back, internal rollback has no effect on external transactions. Applies only to DataSourceTransactionManager.

Isolation level of Spring transactions:

The isolation level of a Spring transaction defines the extent to which a transaction can be affected by other concurrent transactions. Five constants representing the isolation level are defined in the TransactionDefinition interface:

  • ISOLATION_DEFAULT: this is a PlatfromTransactionManager default isolation level, using the database default transaction isolation level, four other correspond to JDBC isolation level; Reading uncommitted data (dirty read, non-repeatable read) is basically not used. Use @transactional (isolation = Isolation.read_uncommitted) when annotating the @transactional method. REPEATABLE_READ SQLSERVER: READ_COMMITTED

  • ISOLATION_READ_UNCOMMITTED: This is the lowest isolation level for a transaction, allowing uncommitted data to be seen by another transaction. This isolation level can result in dirty reads, unrepeatable reads, and phantom reads. (Read uncommitted data (dirty read, non-repeatable read) basically not used)

  • ISOLATION_READ_COMMITTED: Ensures that data modified by one transaction is committed before it can be read by another transaction. Another transaction cannot read uncommitted data (read committed data (unrepeatable reads and phantom reads occur))

  • ISOLATION_REPEATABLE_READ: This transaction isolation level prevents dirty, non-repeatable reads. However, phantom reads can occur, which in addition to ensuring that one transaction cannot read uncommitted data from another transaction, also ensures that the following situation is avoided (unrepeatable reads); (Repeatable reading (phantom reading will occur))

  • ISOLATION_SERIALIZABLE: This is the most expensive but reliable transaction isolation level. Transactions are processed sequentially, avoiding phantom reads in addition to preventing dirty, non-repeatable reads. (Serialization)

Declarative transaction management

1, inapplicationContext.xmlUse XML to configure transactions in configuration files:


<tx:advice id=”txAdvice” transaction-manager=”txManager”>

tx:attributes

<tx:method name=”execute” propagation=”REQUIRED”/>

<tx:method name=”*” propagation=”REQUIRED”/>

</tx:attributes>

</tx:advice>

<aop:advisor advice-ref=”txAdvice” pointcut-ref=”actionPointcut”/>

</aop:config>

2, inapplicationContext.xmlUsing annotations in the configuration file:

Step1: define HibernateTransactionManager Bean component (transaction management)

Step2: enable the annotation configuration of the transaction

step3: Then use the @Transactional annotation in front of the business component’s class definition or in a method, for example: AddCostAction, which is used before the class definition. Transactional(Propagation =Propagation.REQUIRED) Public Class AddCostAction extends BaseAction{…… } (2) DeleteCostAction, @transactional (Propagation =Propagation.REQUIRED) Public String Execute () throws DAOException{… } (3) UpdateCostAction, Transactional(Propagation =Propagation.REQUIRED) Public Class UpdateCostAction extends BaseAction {… } (4) ListCostAction, Use @transactional (readOnly=true, Propagation =Propagation.REQUIRED) public String Execute () throws Exception {…… } Note: If Action is the target, you need to add the proxy-target-class=”true” attribute to tx:annotation-driven, indicating that the CGLIB proxy class is generated with or without the interface.

Programmatic transaction management

Spring, programmatic transactions relies on the 2 categories, respectively is PlatformTransactionManager, and template class TransactionTemplate (recommended). The following details how Spring implements transaction management through this class.

1. Transaction manager configuration

2 Using code in business (to test class presentation)

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { “classpath:spring-public.xml” }) public class test { @Resource private PlatformTransactionManager txManager; @Resource private DataSource dataSource; private static JdbcTemplate jdbcTemplate; Logger logger=Logger.getLogger(test.class); private static final String INSERT_SQL = “insert into testtranstation(sd) values(?) “; private static final String COUNT_SQL = “select count(*) from testtranstation”; @test public void testDelivery (){ DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); / / transaction state class, defined according to the transaction through the PlatformTransactionManager getTransaction method to obtain; TransactionStatus Status = txManager.getTransaction(def); TransactionStatus = txManager.getTransaction(def); jdbcTemplate = new JdbcTemplate(dataSource); int i = jdbcTemplate.queryForInt(COUNT_SQL); System.out.println(” total number of entries in table: “+ I); try { jdbcTemplate.update(INSERT_SQL, “1”); txManager.commit(status); } catch (RuntimeException e) {txManager.rollback(status); } I = jdbctemplate.queryForint (COUNT_SQL); System.out.println(” total number of entries in table: “+ I); }}

3. Use TransactionTemplate

The TransactionTemplate template class uses the following callback interface: Through the implementation of the interface “T doInTransaction(TransactionStatus status)” method to define the operation code for transaction management; TransactionCallbackWithoutResult: Inheritance TransactionCallback interface, provide “void doInTransactionWithoutResult (TransactionStatus status)” convenient interface is used to make it convenient to operate those who do not need to return the value of the transaction code.

DefaultTransactionDefinition class inherited interface, used to simplify the transaction management, transaction management by the template class definition, Mainly through TransactionCallback callback interface or TransactionCallbackWithoutResult callback interface to specify, By calling the class template parameter types for TransactionCallback or TransactionCallbackWithoutResult the execute method to automatically enjoy the transaction management.

Again, as a test class, I’ll show you how to do this:

@Test public void testTransactionTemplate(){ jdbcTemplate = new JdbcTemplate(dataSource); int i = jdbcTemplate.queryForInt(COUNT_SQL); System.out.println(" total number of entries in table: "+ I); TransactionTemplate = new TransactionTemplate(txManager); template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); / / rewrite the execute method implementing transaction management template. Execute (new TransactionCallbackWithoutResult () {@ Override protected void DoInTransactionWithoutResult (TransactionStatus status) {jdbcTemplate. Update (INSERT_SQL, "starve"); // select * from TransactionTemplate; // select * from TransactionTemplate; i = jdbcTemplate.queryForInt(COUNT_SQL); System.out.println(" total number of entries in table: "+ I); }Copy the code

PS: Database knowledge expansion:

Pay attention to transactions and locks:

Transaction is an important tool in database application. It has four attributes of atomicity, consistency, isolation and persistence. We need to use transaction to ensure the correctness of data in many operations. We need to avoid deadlocks and reduce blocking as much as possible in using transactions.

Special attention should be paid to the following aspects: A, the transaction operation process should be as small as possible, and the transaction that can be split should be split. B. There should be no interaction during transaction operation, because the transaction is not finished while the interaction is waiting, and many resources may be locked. C. Transactions access objects in the same order. D. Improve the efficiency of each statement in a transaction. Using indexes and other methods to improve the efficiency of each statement can effectively reduce the execution time of the entire transaction. E, try not to specify the lock type and index. SQL SERVER allows us to specify the lock type and index used by the statement. However, in general, the LOCK type and index selected by SQL SERVER optimizer is optimal for the current data volume and query conditions. But the amount and distribution of data will change in the future. F. You can use a lower isolation level for query, especially for report query. You can select the lowest isolation level (uncommitted read).

2. Database is divided into local transactions and global transactions

Local transaction: Ordinary transaction, ACID that is guaranteed to operate on a single database. Distributed transactions: transactions involving two or more database sources, that is, transactions spanning multiple homogeneous or heterogeneous databases (consisting of local transactions of each database), distributed transactions are designed to ensure ACID of all operations of these local transactions, so that transactions can span multiple databases;