This series is the summary notes of the book “MyBatis: Technical Principles and Practice”.

This is the final installment of the MyBatis series, which covers the integration with Spring and some practical scenarios at work.

Before introducing, summarize the content and writing ideas of the series.

MyBatis is a framework that encapsulates database-related operations, bringing great convenience to our developers. Compared with Hibernate, MyBatis has great flexibility and expansibility, which is very important in high concurrency and high performance applications.

First introduced the JDBC specification, we understand the most primitive and most familiar operation database way, MyBatis is on this basis for encapsulation and abstraction.

Then, the characteristics and core components of MyBatis are introduced to have an overall understanding of it.

After, the detailed introduction of MyBatis configuration, mapper, they are usually used, contact the most, you can use MyBatis for development.

Finally, the reflection and dynamic proxy basis is reviewed, in-depth analysis of MyBatis analysis and operation principle, plug-in and development process, on the one hand, MyBatis core components have a deeper understanding, on the one hand, can better plug-in development, unified processing of SQL.

Series index:

  1. Introduction to JDBC and MyBatis
  2. All configurations of MyBatis
  3. Mapper knows all about it
  4. Reflection and dynamic proxy fundamentals
  5. MyBatis parsing and operating principle
  6. MyBatis plug-in and development process

In practice, it is often used with Spring integration to reduce our workload. Through this introduction, you will learn:

  • Spring basics: IOC, AOP, transaction management;
  • MyBatis-Spring Applications: Configuration and integration
  • Practical Scenarios

Spring IOC and AOP

Understanding the basics of Spring helps you understand integration configuration. Spring technology consists of IOC and AOP, two basic capabilities.

IOC

IOC is called inversion of control and can be understood as follows: With IOC, all objects configured to be managed by Spring are managed by Spring, including the creation and life cycle of objects. In this way, when retrieving objects of a class, Spring decides which object to return without specifying it.

In this way, control of object creation is transferred from the business code to Spring, known as inversion of control.

AOP

AOP is called section-oriented programming. The so-called section-oriented programming means that some logic processing codes are inserted into normal logic, such as logging and transaction management codes, among which logging and transaction management are aspects. Spring AOP can uniformly insert aspect processing code for affected class methods through simple configuration without modifying the logic of the original method.

Spring AOP is implemented through dynamic proxies, using JDK dynamic proxies when Spring services contain interface descriptions, and CGLIB proxies otherwise.

Finally, a brief explanation of aOP-related concepts to help you understand its configuration:

  • Pointcut: After Spring generates a proxy object, when invoking a service method, the Invoke method of InvitationHandler will be called. Which methods need to be intercepted for special processing? This is the pointcut, which Spring can configure with regex.
  • Aspects: As described above, the logical objects that need to be dealt with, such as logging and transaction management, are aspects;
  • Connection point: it is in the program run according to different notice to realize the program segment, notice including, pre notice, post notice, abnormal notice, normal return notice, circular notice;

Spring Transaction Management

When writing business code, a business method may involve multiple tables or multiple SQL statements, the same table data may be accessed at the same time, the transaction control of the database is very important, through Spring AOP and Spring transaction management, can greatly reduce our code, the transaction management of various scenarios is also very convenient.

Transaction isolation level
  • Read uncommitted: A dirty read problem may occur where one transaction reads uncommitted data from another transaction.
  • Read committed: The unrepeatable read problem may occur. Different data may be read for the same record before and after the same transaction.
  • Repeatable read: Phantom read problems may occur. For delete and insert records, the number of records returned by the same query condition may be different for the same transaction.
  • Serialization: All operations are executed sequentially;

MySql default isolation level is repeatable read.

Propagation behavior

Spring defines seven propagation behaviors, which can be configured according to different scenarios. Here are a few examples:

  • PROPAGATION_REQUIRED: If a transaction exists, use the current one, otherwise start a transaction.
  • PROPAGATION_SUPPORTS: If a transaction exists, the current transaction is supported, otherwise it executes non-transactionally.
  • PROPAGATION_REQUIRES_NEW: Always start a new transaction, even if one exists
  • PROPAGATION_NOT_SUPPORTED: Always execute non-transactionally, suspending something that already exists

Spring’s default propagation behavior is PROPAGATION_REQUIRED.

MyBatis-Spring integration configuration

Knowing Spring’s IOC, the integration configuration is relatively easy, and besides writing business SQL, transactions are an important part of it, which Spring AOP and transaction management help us solve.

MyBatis provides the function of seamless connection with Spring, mainly through MyBatis -spring-x.x.x.jar implementation, the following is the process of integration configuration:

Configuring a Data Source

The javax.sql.DataSource interface can be implemented using the C3P0 implementation.

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${c3p0.driverClass}"></property>
		<property name="jdbcUrl" value="${c3p0.jdbcUrl}"></property>
		<property name="user" value="${c3p0.user}"></property>
		<property name="password" value="${c3p0.password}"></property>
		<property name="acquireIncrement" value="${c3p0.acquireIncrement}"></property>
		<property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
		<property name="maxIdleTime" value="${c3p0.maxIdleTime}"></property>
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
		<property name="minPoolSize" value="${c3p0.minPoolSize}"></property>
</bean>
Copy the code
Configuration SqlSessionFactory

It is to generate the SqlSession, component provides org. Mybatis. Spring. SqlSessionFactoryBean class to configure for us.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <! - automatic scanning entity directory to match the alias - > < property name = "typeAliasesPackage" value = "com. Xiaomi. KFS. MCC. Personal preference, com.xiaomi.kfs.authority.core" /> <! <property name="mapperLocations" value="classpath*:context/mybatis/* mapper.xml "/> <! <property name="configLocation" value=" clasSPath :mybatis-config.xml"></property> </bean>Copy the code

The configuration file mybatis-config.xml is described in the previous article and will not be written again.

Configure automatic mapper bean scanning:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.xiaomi.kfs.mcc.persistence,com.xiaomi.kfs.mcc.workorder, com.xiaomi.kfs.authority.core" />
		<property name="annotationClass" value="com.xiaomi.common.annotation.MyBatisRepository" />
</bean>
Copy the code
Configuration of the transaction

Use Spring AOP to manage transactions.

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <! @transactional --> <tx:annotation-driven transaction-Manager ="transactionManager" />Copy the code

Application Scenarios

In practice, there may be many usage scenarios, and the following will briefly introduce some of these scenarios to illustrate the implementation ideas.

Database BLOB field reads and writes

MyBatis provides BlobTypeHandler for type mapping, which automatically converts byte[] types to BLOB types.

But more often than not, files are stored in a dedicated file server where the database stores the file path.

Batch update

To improve database performance, change defaultExecutorType to BATCH. In this case, if there are multiple SQL transactions in a transaction, the SQL is sent to the database only after the commit.

Note, however, that if the program context relies on the inserted data primary key, you can actively send the currently cached SQL to the database for execution by calling the flushStatements method of sqlSession.

Calling a stored procedure

MyBatis supports stored procedures and encapsulates them. The specific configuration process is not described in detail here.

table

MyBatis allows you to pass table names as parameters to SQL, which is easy to implement.

paging

MyBatis has paging, implemented through RowBounds, but it has the problem of querying all the results in a single SQL query and returning data from row to row. You can write a plug-in to rewrite the SQL for paging and uniform processing.

Using enumerated types

As mentioned in the previous article, this can be easily implemented by customizing typeHandler.

Then read RabbitMQ In Action: Deploying Distributed Message queues efficiently to summarize and share.

Please scan the qr code below and follow my personal wechat official account ~