Configuration and use of Mybatis and Spring integration

After Mybatis is integrated with Spring

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database.

After integrating mybatis through Spring, our workload has been greatly reduced. Let's take a look at where the configuration file of mybatis is.

1. Mybatis configuration file

As we all know, mybatis is a persistence layer framework that encapsulates the database, and the corresponding operation layer is our Dao layer, so we also configure mybatis in dao.xml in the Spring configuration file.

<?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:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis过程 -->

<!-- 1.配置数据库相关参数properties的属性:设置在spring-properties中 -->
<!-- 2.数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30" />
<property name="minPoolSize" value="10" />
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false" />
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000" />
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2" />
</bean>

<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 扫描entity包 使用别名 -->
<property name="typeAliasesPackage" value="com.comment.george.entity" />
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>

<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.comment.george.dao" />

</bean>
</beans>

This is the setting of mybatis. For the connection pool properties, that is, our database properties, for our usual database management needs, we take out the database property list to form a JDBC.properties file for storage, which is stored in spring The values ​​in the xml file are obtained through EL expressions.

Similarly, we also need to set the global environment of mybatis, which requires another file mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
<plugins>
    <plugin interceptor="com.comment.george.dao.interceptor.PageInterceptor"/>
</plugins>

</configuration>

Here we configure the global properties, enable related services, and configure the interceptors we wrote ourselves.

2. The use of mybatis

Through the configuration file set above, we can use myabtis

2.1 Annotation of mybatis

@param: Parameter specification via @Param ("id") can use the correct parameters in the mapper.xml mapping file.

2.2 Mybatis xml file.

The most important thing in mybatis is the mapping file mapper.xml that we want to configure.

Take a look at the tags in the xml file and what attributes are there:

  • namespace: used to specify the classpath
  • select: SQl statement for writing select
  • update: sql statement for writing update
  • delete: the sql statement used to write delete
  • insert: the sql statement used to write the insert

Return result:

  • resultType:
    We can specify the basic data type or simple bean as the return value to set through resultType. Simple bean refers to the case where the bean does not contain other beans.

  • resultMap:
    When the resultType cannot meet the requirements, we need to specify the type we need and tell Mybatis to parse it.

To use resultMap in the returned result, we need to define our own resultMap first, whose structure is as follows:

<resultMap id="businessMap" type="Business">//id为我们在resultmap中所要填写的名称 type为我们所指定的复杂bean
    <id property="id" column="id"/>//property为我们bean内的属性名称, column为数据库中列的名称 id是设为主键,提高查找效率
    <result property="title" column="title"/>
    <result property="subTtile" column="sub_title"/>
    <association property="cityDic" javaType="Dic">//association为联合,我们要为主Bean中的子Bean的属性进行赋值,需要通过这个标签进行指定, javaType为子bean的属性名称
        <result property="cityDic" column="city_name"/> 子bean的属性名称以及bean的属性名
    </association>
    <association property="categoryDic" javaType="Dic">
        <result property="categoryDic" column="category_name"/>
    </association>
</resultMap>

There are two tags commonly used in resultmap:
association and collection:

  • associations are usually used in singleton beans.

  • collection is usually used in ListBean arrays.

2.3 Introduction and use of mybatis interceptor

We usually have to query through some settings returned by the front-end page. If we perform fuzzy query and attribute modification for each requirement, it is too troublesome, so our Mybatis interceptor is on the scene, we pass Mybatis interceptor Sql statements that have not been executed can be intercepted and filtered, and Sql statements that meet the requirements can be modified to achieve the purpose of paging or conditional query.

To implement our own interceptor interface, we need to inherit the interceptor interface and implement

There are three methods in the interceptor interface:

intercept method: The correct result after we intercept is in this method, we transform the sql statement in this method

plugin method: return the correct sql object through dynamic proxy and intercept

setProperties method: Set the property value to let the interceptor act according to the property value.

The method of using the interceptor is divided into two steps:
1. Inheriting and implementing the interface of
the interceptor 2. Registering the interceptor in the corresponding DAO.xml file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325164331&siteId=291194637