what? The reason why I am never afraid of interviews and job hunting is because I saw this spring affairs!

In addition, I have collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. The following are just some screenshots. If you want information, you can also click 1149778920 to receive the secret code CSDN.
Insert picture description here

1. About transaction control

A transaction is a series of actions. They are integrated together to form a complete unit of work. These actions must all be completed. If one fails, the transaction will roll back to the initial state, as if nothing happened. .

1.1 Transaction Control API in Spring

PlatformTransactionManager 接口提供事务操作的方法,包含三个具体的操作

public interface PlatformTransactionManager extends TransactionManager {
    
    
    // 获取事务状态信息
    TransactionStatus getTransaction(@Nullable TransactionDefinition var1) throws TransactionException;

    // 提交事务
    void commit(TransactionStatus var1) throws TransactionException;

    // 回滚事务
    void rollback(TransactionStatus var1) throws TransactionException;
}

Implementation classes commonly used in development:

org.springframework.jdbc.datasource.DataSourceTransactionManager :使用Spring JDBC或iBatis进行持久化数据时使用

Structure of transaction control interface in spring
Insert picture description here

1.1.2 TransactionDefinition

The definition information object of the transaction includes the following methods:

  • Get the name of the transaction object: String getName()

  • Get transaction isolation level: int getIsolationLevel()

  • Get transaction propagation behavior: int getPropagationBehavior()

  • Get transaction timeout: int getTimeout()

  • Get whether the transaction is read-only: boolean isReadOnly()

1.1.3 TransactionStatus

Describes the status information of the transaction object at a certain point in time, including 6 specific operations:

Refresh transaction: void flush()

  • Get whether there is a storage point: boolean hasSavepoint()

  • Get whether the transaction is complete: boolean isCompleted()

  • Get whether the transaction is new: boolean isNewTransaction()

  • Get whether the transaction is rolled back: boolean isRollbackOnly()

  • Set transaction rollback: void set RollbackOnly()

1.2 Transaction isolation level

The isolation sector of the transaction reflects the processing attitude when the transaction is submitted for concurrent access

1.2.1 The level of transaction isolation

  • ISOLATION_DEFAULT default level, the isolation level is determined by the DBA default setting, belonging to one of the following
  • ISOLATION_READ_UNCOMMITTED means that a transaction can read the data of another uncommitted transaction. There will be dirty reads, non-repeatable reads, and phantom reads (the lowest isolation level, but high concurrency)
  • ISOLATION_READ_COMMITTED means that a transaction can only read data after another transaction is submitted to solve the dirty read problem. There will be non-repeatable read, phantom read problems (lock the row being read, applicable to most systems, Oracle default level)
  • ISOLATION_REPEATABLE_READ is when starting to read data (the transaction is opened), no more modification operations are allowed to solve the problem of non-repeatable reading. There will be phantom reading problems (lock all rows read, MYSQL default level)
  • ISOLATION_SERALZABLE is the highest transaction isolation level. Under this level, transactions are serialized and executed sequentially, which can avoid dirty reads, non-repeatable reads, and phantom reads. However, this transaction isolation level is inefficient and consumes database performance, so it is generally not used.

The transaction isolation level is increased from top to bottom. The higher the isolation level, the better the integrity and consistency of data can be guaranteed. However, the consumption of database performance increases successively, and the efficiency of concurrent execution decreases successively.
The default isolation level of most databases is Read Commited, such as SqlServer and Oracle. The
default isolation level of a few databases is: Repeatable Read For example: MySQL InnoDB

1.2.2 Three kinds of problems that appear when the database is read

① Dirty reads: read dirty data.

That is to say, for example, the uncommitted (still cached) data of transaction A is read by transaction B. If transaction A fails and rolls back, the data read by transaction B will be wrong.

② Non-repeatable reads: Data cannot be read repeatedly.

For example, the value of the data price is read in two places in transaction A. In the first reading, the price is 100, and then transaction B changes the value of price to 200; transaction A reads it again, and it turns out that the price has become 200, causing transaction A data confusion.

③ phantom reads: phantom read data.

This is similar to non-repeatable reads, and it is also a problem of inconsistency in multiple reads in the same transaction. But the inconsistency of non-repeatable reads is because the value of the data he wants to fetch has been changed (such as price), and the inconsistency of the data read by phantom reads is because his conditional data set has changed.

For example: execute Select account.id where
account.name="Bruce*", and read 6 qualified IDs for the first time; for the second read, the name of an account is changed to "dd" due to transaction B Changed to "Bruce1", and as a result, 7 data were retrieved.

The key point of non-repeatable reading is to modify: the same condition, two readings will find that the value is different;

The key point of the phantom reading is to add or delete: the same condition, the number of records obtained in two readings is different

1.2.3 The correlation between data isolation level and problems

Insert picture description here

1.3 The dissemination of affairs

  • REQUIRED: If there is no transaction currently, create a new transaction, if there is already a transaction, join it. General choice (default value)

  • SUPPORTS: support the current transaction, if there is no transaction currently, it will be executed in a non-transactional manner (no transaction)

  • MANDATORY: Use the current transaction, if there is no transaction currently, throw an exception.

  • REQUERS_NEW: Create a new transaction. If it is currently in a transaction, suspend the current transaction.

  • NOT_SUPPORTED: Perform the operation in a non-transactional manner. If there is a transaction currently, the current transaction is suspended.

  • NEVER: Run in non-transactional mode. If there is a transaction currently, an exception is thrown.

  • NESTED: If a transaction currently exists, it will be executed within a nested transaction. If there is no transaction currently, perform a similar operation to REQUIRED.

1.4 Timeout

Refers to the longest waiting time after the transaction is committed, and it will automatically fail if the time is exceeded. The default value is -1, there is no time limit. If so, set it in seconds.

1.5 Is it a read-only transaction

Read-write transactions: open transactions when adding, deleting, or modifying

Read-only transaction: when the query is executed, the transaction will also be opened

2. XML-based transaction control configuration

2.1 Configuration steps

Configure the transaction manager
Configure the notification of the transaction.
At this time, we need to import the constraint tx namespace and constraint of the transaction. At the same time, we also need to use the tx:advice tag of aop to configure the transaction notification

id: a unique identifier for the transaction notification
transaction-manager: provide a transaction manager reference for the transaction notification
3. Configure the general entry point expression in AOP

4. Establish the correspondence between transaction notifications and entry point expressions

5. The attributes of the configuration transaction are inside the tx:advice tag of the transaction notification

2.2 Configure the properties of the transaction

  • isolation: used to specify the isolation level of the transaction. The default value is DEFAULT, which means to use the default isolation level of the database.
  • propagation: used to specify the propagation behavior of the transaction. The default value is REQUIRED, which means there must be a transaction, the choice of addition, deletion and modification. The query method can choose SUPPORTS.
  • read-only: Used to specify whether the transaction is read-only. Only the query method can be set to true. The default value is false, which means read and write.
  • timeout: Used to specify the timeout period of the transaction, the default value is -1, which means never timeout. If a value is specified, the unit is in seconds.
  • rollback-for: Used to specify an exception. When the exception occurs, the transaction rolls back, and when other exceptions occur, the transaction does not roll back. There is no default value. Indicates that any exceptions are rolled back.
  • no-rollback-for: Used to specify an exception. When the exception occurs, the transaction does not roll back, and the transaction rolls back when other exceptions occur. There is no default value. Indicates that any exceptions are rolled back.
    Code example:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/base_crud"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 1.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 2.配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"></tx:method>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!-- 3.配置AOP -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* cn.bruce.service.impl.*.*(..))"/>
	<!-- 4.建立事务通知和切入点表达式的对应关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>

    <!-- 配置dao -->
    <bean id="accountDao" class="cn.bruce.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置service -->
    <bean id="accountService" class="cn.bruce.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

</beans>

3. Annotation-based transaction control configuration

3.1 Configuration steps
① Write configuration class

② Inject the object into the IoC container for management

③ Add transaction notes to the business and specify transaction attributes

Code example:

① Configure spring

@Configuration// 声明为配置类
@ComponentScan("cn.bruce")// 声明需要扫描的包
@Import({
    
    JdbcConfig.class, TransactionConfig.class})// 导入其他配置类
@PropertySource("jdbcConfig.properties")// 导入配置文件
@EnableAspectJAutoProxy(proxyTargetClass = true)// 开启注解支持
@EnableTransactionManagement// 开启事务控制
public class SpringConfiguration {
    
    
}

② Configure jdbc

public class JdbcConfig {
    
    

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建数据源对象
     * @return
     */
    @Bean("dataSource")
    public DataSource creatDataSource() {
    
    
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 创建JdbcTemplate
     * @param dataSource
     * @return
     */
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate creatJdbcTemplate(DataSource dataSource) {
    
    
        return new JdbcTemplate(dataSource);
    }
}

③ Configure transaction controller

public class TransactionConfig {
    
    

    /**
     * 用于创建事务管理器对象
     * @param dataSource
     * @return
     */
    @Bean(name = "transactionManager")
    public PlatformTransactionManager creatTransactionManager(DataSource dataSource) {
    
    
        return new DataSourceTransactionManager(dataSource);
    }
}

④ Inject Dao and Service layer objects into the IoC container through @Repository and @service annotations
⑤ Use @Transactional annotations in the business layer for transaction configuration

// 进行读写型事务配置
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
@Override
public void transfer(String sourceName, String targetName, Float money) {
    
    

    System.out.println("开始进行转账操作。。。");

    Account source = accountDao.getAccountByName(sourceName);

    Account target = accountDao.getAccountByName(targetName);

    source.setMoney(source.getMoney() - money);

    target.setMoney(target.getMoney() + money);

    accountDao.updateAccount(source);

    int i = 1/0;

    accountDao.updateAccount(target);

    System.out.println("转账完成。。。");
}

⑥ Write test class to test

3.2 Notes involved

@Transactional This annotation is equivalent to tx:attributes****</tx:attributes> in the xml configuration
for transaction configuration, and its attribute meaning is the same as in xml

This annotation is used on interfaces, classes, and methods:

  • Appears on the interface, indicating that all implementation classes of this interface have transaction support

  • Appears on the class, indicating that all methods of the class have transaction support

  • Appears on the method, indicating that this method has transaction support
    . Priorities in the above three positions: Method> Class> Interface

to sum up:

No matter which company it is, it attaches great importance to Spring framework technology and foundation, so don't underestimate any knowledge. The interview is a two-way selection process. Don't go to the interview with a fearful attitude, which is not conducive to your own performance. At the same time, you should not only look at salary, but also whether you really like this company and whether you can really get exercise. In fact, I have written so much, just my own summary, not necessarily applicable to everyone, I believe that after some interviews, everyone will have these feelings.

In addition, I have collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. The following are only some screenshots. If you want information, you can also click 795983544 to receive the secret code CSDN.

Insert picture description here

Guess you like

Origin blog.csdn.net/w1103576/article/details/109078814