Mybatis:mybatis and spring integration and practical scenarios

Source: Internet
Author: User
Tags aop

This series is a summary note of the book "MyBatis: Technical Principles and practice".

This is the last article in the mybatis"series, which mainly introduces the integration with spring and some practical scenarios in the work.

Before the introduction, the overall summary of the content of the series and writing ideas.

MyBatis is a framework that encapsulates database-related operations and offers great convenience to our developers, with great flexibility and extensibility over hibernate, which is important in high-concurrency performance applications.

First, we introduce the specification of JDBC, understand the way of our most primitive and familiar operation database, and MyBatis is to encapsulate and abstract on this basis.

Then, it introduces the characteristics and core components of MyBatis, and has an overall understanding of it.

Later, the detailed introduction of MyBatis configuration, mapper, they are usually used, the most contact, can be very good use of mybatis development.

Finally, we review the reflection and Dynamic Agent Foundation, deeply analyze the analysis and operation principle of mybatis, plug-in and development process, on the one hand, the core components of MyBatis have more in-depth understanding, on the other hand can better plug-in development, SQL Unified processing.

In practice, it is often used in conjunction with spring integration to reduce our workload, and through this introduction, you will learn:

    • Basic knowledge of Spring: IOC, AOP, transaction management;
    • Mybatis-spring Applications: Configuration and Integration
    • Introduction to Practical scenarios
Spring IOC and AOP

Understanding the basics of spring helps to understand the integration configuration, and spring technology is primarily comprised of two basic functions of IOC and AOP.

IOC

The IOC, called inversion of control, can understand this: before we get a class object, we go to the new one, we have to determine which implementation class is, with IOC, all the objects that are configured for spring management are managed by spring, including object creation and life cycle, so that when you get to the object of the class, There is no need to display the specified, and it is up to spring to decide which object to return.

In this way, object creation, control is shifted from business code to spring, called control inversion.

Aop

AOP, called aspect-oriented programming, is about inserting some logic-processing code into normal logic, such as inserting logging, transaction management, and so on, where logging and transaction management are facets. Spring AOP can uniformly insert slice processing code into the affected class methods with simple configuration without modifying the original method logic.

Spring AOP is implemented through dynamic proxies, and when spring's services contain interface descriptions, the JDK dynamic agent is used, otherwise the cglib agent is used.

Finally, a simple description of the AOP-related concepts makes it easy to understand its configuration:

    • Pointcut: After spring generates the proxy object, when the service method is invoked, the Invoke method of Invitationhandler is called, which methods need to be intercepted, the special processing is done, this is the pointcut, spring can be configured by regular;
    • Facets: The above has been introduced, log records, transaction management, such as the need to deal with the logical object, is the plane;
    • Connection point: It is in the program running in accordance with different notifications to achieve the program segment, notification includes, pre-notification, post-notification, exception notification, after normal return notification, surround notification;
Spring Transaction Management

When writing business code, one business method may involve multiple tables or multiple SQL statements, the same table data may be accessed concurrently, the transaction control of the database is important, and with spring AOP and Spring transaction management, we can greatly reduce our code, and the transaction management of various scenarios is very convenient.

Transaction ISOLATION LEVEL
    • READ UNCOMMITTED: A dirty read problem may occur, and one transaction reads uncommitted data from another transaction;
    • Read Committed: There may be non-repeatable read problems, for the same record, before and after the same transaction may read different data;
    • REPEATABLE READ: There may be a phantom reading problem, for deleting and inserting records, the same query condition, the number of records returned by the same transaction may be different;
    • Serialization: All operations are executed sequentially;

MySQL default isolation level is repeatable read.

Propagation behavior

The propagation behavior, refers to the method between the call, how the transaction is passed, in spring defines 7 propagation behavior, can be configured according to different scenarios, do not introduce each one, to give a few instructions:

    • Propagation_required: If there is a transaction, the current transaction is used, otherwise a transaction is opened;
    • Propagation_supports: If there is a transaction, the current transaction is supported, otherwise non-transactional execution;
    • Propagation_requires_new: Always open a new transaction, even if there is a transaction exists;
    • Propagation_not_supported: Always executes in a non-transactional execution, suspending something that already exists;

Spring's default propagation behavior is propagation_required.

Mybatis-spring Integrated Configuration

Understanding the IOC of spring, the integration configuration is relatively straightforward, and, in addition to the writing of business SQL, transaction is a very important part, Spring AOP and transaction management to help us solve.

MyBatis provides the ability to seamlessly interface with spring, mainly through the Mybatis-spring-x.x.x.jar implementation, the following is the process of integration configuration:

Configure the data source

Using the C3P0 implementation, as long as the implementation of the Javax.sql.DataSource interface can be.

<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>
Configure Sqlsessionfactory

It is generated sqlsession, the component provides the Org.mybatis.spring.SqlSessionFactoryBean class to us to configure.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <!-- 自动扫描entity目录以匹配别名 -->        <property name="typeAliasesPackage" value="com.xiaomi.kfs.mcc.persistence, com.xiaomi.kfs.authority.core" />        <!-- 显式指定Mapper文件位置 -->        <property name="mapperLocations" value="classpath*:context/mybatis/*Mapper.xml" />        <!-- 指定mybatis配置文件 -->        <property name="configLocation" value="classpath:mybatis-config.xml"></property></bean>

Configuration file Mybatis-config.xml Earlier in this article, it is not written again.

Configure automatic scanning of mapper beans:
<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>
Configuring transactions

Manage transactions using spring AOP.

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" /></bean><!-- 使用annotation定义事务 @Transactional --><tx:annotation-driven transaction-manager="transactionManager" />
Introduction to Usage scenarios

Actual work, there may be a lot of usage scenarios, the following will be a brief introduction of these scenarios, explain the implementation of ideas.

Database blob field Read-write

For files, in a database, typically stored in BLOB fields, MyBatis provides blobtypehandler for type mapping, which can convert byte[] types and blob types automatically.

But more often, we will store the files in a file server, the database storage file path.

Batch Update

Batch updates can help improve database performance by modifying Defaultexecutortype, which is set to batch, so that if a transaction has more than one SQL, SQL to the database is sent only after a commit.

Note, however, that if you rely on the inserted data primary key in the context of the program, you can actively send the currently cached SQL to the database execution by calling the Flushstatements method of sqlsession.

Call a stored procedure

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

Sub-table

If the system database is large enough to reduce the pressure on a single table by a table, MyBatis allows the table name to be passed as a parameter to SQL, which is easy to implement.

Page out

MyBatis has a paging function, implemented through Rowbounds, but it has a problem, it queries all the results in a single SQL, and then returns the data based on the first few to the first. You can do this by writing a plug-in, overriding the SQL for paging, and processing it uniformly.

Using enum types

As previously described, the custom Typehandler can be easily implemented.

Start reading "RABBITMQ: Deploy distributed Message Queuing efficiently, and summarize and share.

Welcome to scan the QR code below, follow my personal public number ~

Mybatis:mybatis and spring integration and practical scenarios

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.