mybatis advanced features

Database transaction management

Through annotations: Add the @Transactional annotation on the method that requires transaction management. This annotation can be used on classes or methods. Enable the transaction manager in the configuration file and specify the type of transaction manager, connection pool and other related information.
Example

java
@Transactional
public void updateUserInfo(UserInfo userInfo) {
    // 执行更新操作
    // ...
}

Through XML configuration: Use tags in the Mapper XML file to configure the transaction manager, and the tx:advice tag to configure the transaction propagation behavior and exception handling strategy.

xml
<transactions>
    <transactionManager type="JDBC">
        <dataSource type="POOLED">
            <!-- 配置数据源 -->
        </dataSource>
    </transactionManager>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
</transactions>

In the configuration file, you also need to configure information related to the transaction manager and data source.

xml
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC">
            <dataSource type="POOLED">
                <!-- 配置数据源 -->
            </dataSource>
        </transactionManager>
    </environment>
</environments>

It should be noted that the type of transaction manager and the configuration of the data source need to be configured according to the specific database and connection pool.

In addition, MyBatis also supports manual submission and rollback operations of transactions. The commit() and rollback() methods of the SqlSession instance can be used to manually control the submission and rollback of transactions.

java
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    // 执行数据库操作
    sqlSession.commit();
} catch (Exception e) {
    sqlSession.rollback();
} finally {
    sqlSession.close();
}

Configuring and managing transactions in the above way can ensure the data consistency and transaction reliability of MyBatis when performing database operations.

Batch processing

Batch processing refers to the function of executing multiple database operation statements at one time. This can improve performance in certain scenarios.

  • In MyBatis, use the insert, update, and delete methods of SqlSession to perform batch processing. These methods can accept a collection of multiple parameters, each parameter representing a database operation. For example:
java
List<User> userList = new ArrayList<>();
userList.add(new User("user1"));
userList.add(new User("user2"));

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
    sqlSession.insert("insertUser", userList);
    sqlSession.commit();
} finally {
    sqlSession.close();
}
  • In the above example, insertUser is an insert statement in Mapper, and userList is a collection containing multiple User objects, representing multiple insert operations. After calling the insert method, MyBatis will perform an insertion operation for each User object as a parameter.

  • It should be noted that in order to improve the performance of batch processing, it is usually necessary to set the autoCommit attribute of SqlSession to false and manually call the commit method to submit the transaction after executing the batch processing.

  1. MyBatis also provides a more efficient way to perform batch processing, using bulk insert/update/delete statements. In this way, you can define a method with a return type of int in the Mapper interface, and use the @InsertProvider, @UpdateProvider, and @DeleteProvider annotations to specify the corresponding dynamic SQL provider. For example:
java
@Mapper
public interface UserMapper {
    @InsertProvider(type = BatchInsertProvider.class, method = "insert")
    int batchInsert(List<User> userList);
}

public class BatchInsertProvider {
    public String insert(Map<String, Object> map) {
        List<User> userList = (List<User>) map.get("list");
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO user (username) VALUES ");
        for (User user : userList) {
            sb.append("(#{item.username}),");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}

List<User> userList = new ArrayList<>();
userList.add(new User("user1"));
userList.add(new User("user2"));

int result = userMapper.batchInsert(userList);
  1. In the above example, BatchInsertProvider is a dynamic SQL provider that dynamically generates batch insert statements based on the parameters passed in. The batchInsert method accepts a collection containing multiple User objects and returns the number of successfully inserted records.
    It should be noted that when using batch insert/update/delete statements, the return type of the corresponding Mapper method must be int, indicating the number of records inserted/updated/deleted.

Plug-in extension

Plug-ins are components used to extend and enhance the functionality of the MyBatis framework. It can intercept the execution process of MyBatis and implement some custom logic.
Commonly used MyBatis plug-in extensions

  1. Interceptor: The Interceptor interface can intercept method calls at various stages of MyBatis execution and add custom logic. Common uses include logging, permission control, result set processing, etc.
  2. Type Handler: The type handler is used to convert Java types and data types in the database. You can customize type conversion logic by implementing the TypeHandler interface to support custom data types.
  3. Parameter Handler: The parameter handler is used to convert Java objects into parameters of SQL statements. By implementing the TypeHandler interface, customized parameter conversion logic can be implemented.
  4. Data Source: MyBatis uses the JDBC connection pool by default to manage database connections. By implementing the DataSource interface, you can customize the data source to support other connection pools.

Persistence and ORM

  1. Persistence is the program's data, which is transformed between transient state (new) and persistent state (database, etc.). Conversion via database operations.
    • Transient state refers to the state of an object before it is persisted to the database. In the transient state, the object's properties may have been assigned values, but these changes have not yet been saved to the database.
    • Persistent state refers to the persistent state of objects in the database. It provides convenient database access and operation methods, and supports caching to improve query efficiency.
  2. ORM.(O=javaBean)(R=relational database)(M=mapping)
    • JavaBeans refer to Java classes that follow specific naming conventions and specifications and are used to encapsulate data and provide methods for accessing this data. It is a programming specification in the Java language.
    • Relational Database refers to a database management system that uses a relational model. The relational model, proposed by Edgar Corder, organizes data into tables, which are composed of rows and columns. A relational database represents the connection between entities by establishing relationships between different tables (through primary keys and foreign keys).
    • Mapping is a widely used concept that has different meanings and functions in different fields, but the core concept is the process or rule of associating one object or value to another object or value.
    • Note: These three aspects of ORM must be consistent. Changes in any part must be detected together.

caching mechanism

  1. L1 cache
    • Session level caching.
    • It is available by default and does not need to be turned on manually.
    • Threads are not shared.
    • When the session is closed or flushed. The session is cleared.
  2. L2 cache
    • sessionFactroy level caching. Selects in the same namespace will be cached.
    • Caching is not enabled by default. Need to be turned on manually.
    • Thread sharing.
    • When additions, deletions and modifications are made, the cache will be cleared.
  3. Steps to enable second level cache
    • In the main configuration file of mybatis, enable caching
<configuration>
   <settings>
      <setting name="cacheEnable" value="true"/>
      <setting name="lazyLoadingEnabled" value="false"/>
   </settings>
</configuration>
  • Setting cache in mapper
<cache
  eviction="FIFO"    // 回收策略
  flushInterval="60000"  // 缓存刷新的间隔时间
  size="512"         // 缓存大小
  readOnly="true" />  // 默认时false,表示其他线程调用都是复制缓存对象。如果为true,线程使用的时原始的缓存对象

Guess you like

Origin blog.csdn.net/m0_65491952/article/details/132320959