摘要: 本文结合《Spring源码深度解析》来分析Spring 5.0.6版本的源代码。若有描述错误之处,欢迎指正。

了解了MyBatis的独立使用过程后,我们再看看它与Spring整合的使用方式,比对之前的示例来找出Spring究竟为我们做了哪些操作来简化程序员的业务开发。由于在之前示例基础上做更改,所以,User与UserMapper保持不变。

(1)Spring配置文件。

配置文件是Spring的核心,Spring的所有操作也都是由配置文件开始的,所以,我们的示例也首先从配置文件开始。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"
lazy-init="true">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/> <!-- 配置连接池初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<!-- 配置获取连接等待超时的时间,单位是毫秒 -->
<property name="maxWait" value="${jdbc.maxWait}"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="select 1"/>
<property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
<property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
<property name="testOnReturn" value="${jdbc.testOnReturn}"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}"/>
<property name="maxPoolPreparedStatementPerConnectionSize"
value="${jdbc.maxPoolPreparedStatementPerConnectionSize}"/>
<!-- 统计sql filter -->
<property name="proxyFilters">
<list>
<bean class="com.alibaba.druid.filter.stat.StatFilter">
<property name="mergeSql" value="true"/>
<property name="slowSqlMillis" value="${jdbc.slowSqlMillis}"/>
<property name="logSlowSql" value="true"/>
</bean>
</list>
</property>
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.cellphone.uc.repo.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean> </beans>

对比之前独立使用MyBatis的配置文件,我们发现,之前在environments中设置的dataSource被转移到了Spring的核心配置文件中管理。而且,针对于MyBatis,注册了org.mybatis.spring.SqlSessionFactoryBean类型bean,以及用于映射接口的org.mybatis.spring.mapper.MapperFactoryBean,这两个bean的作用我们会在稍后分析。

之前我们了解到,MyBatis提供的配置文件包含了诸多属性,虽然大多数情况我们都会保持MyBatis原有的风格,将MyBatis的配置文件独立出来,并在Spring中的org.mybatis.spring.SqlSessionFactoryBean类型的bean中通过configLocation属性引入,但是,这并不代表Spring不支持直接配置。以上面示例为例,你完全可以省去mybatis-config.xml,而将其中的配置以属性的方式注入到SqlSessionFactoryBean中,至于每个属性名称以及用法,我们会在后面的章节中进行详细的分析。

(2)MyBatis配置文件。

对比独立使用MyBatis时的配置文件,当前的配置文件除了移除environments配置外并没有太多的变化。

<?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>
<setting name="cacheEnabled" value="false"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="REUSE"/>
</settings>
<!--类型命名-->
<typeAliases>
<typeAlias alias="User" type="org.cellphone.uc.repo.po.User"/>
</typeAliases>
<!--映射器-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>

(3)映射文件(保持不变)。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.cellphone.uc.repo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="org.cellphone.uc.repo.po.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Apr 21 15:38:35 CST 2018.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap> <sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Apr 21 15:38:35 CST 2018.
-->
id, username, age
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Apr 21 15:38:35 CST 2018.
-->
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=BIGINT}
</select>
<insert id="insert" parameterType="org.cellphone.uc.repo.po.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Apr 21 15:38:35 CST 2018.
-->
insert into user (id, username, password,
sex, age, status, create_tm
)
values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
</mapper>

(4)测试。

至此,我们已经完成了Spring与 MyBatis的整合,我们发现,对于MyBatis方面的配置文件,除了将dataSource配置移到Spring配置文件中管理外,并没有太多变化,而在Spring的配置文件中又增加了用于处理MyBatis的两个bean。

Spring整合MyBatis的优势主要在于使用上,我们来看看Spring中使用MyBatis的用法。

public class UserServiceTest {

    public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/application.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
User user = userMapper.selectByPrimaryKey(32L);
System.out.println("name: " + user.getUsername() + "| age: " + user.getAge());
}
}

测试中我们看到,在Spring中使用MyBatis非常方便,用户甚至无法察觉自己正在使用MyBatis,而这一切相对于独立使用MyBatis时必须要做的各种冗余操作来说无非是大大简化了我们的工作量。

Spring整合MyBatis(二)Spring整合MyBatis的更多相关文章

  1. [Spring] 学习Spring Boot之二:整合MyBatis并使用@Trasactional管理事务

    一.配置及准备工作 1.在 Maven 的 pom 文件中新增以下依赖: <dependency> <groupId>mysql</groupId> <art ...

  2. <Spring Data JPA>二 Spring Data Jpa

    1.pom依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  3. spring boot(二)整合mybatis plus+ 分页插件 + 代码生成

    先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...

  4. Spring Boot系列二 Spring @Async异步线程池用法总结

    1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent.Executor Spring 已经实现的异常线程池: 1. SimpleAsyncT ...

  5. spring boot 学习(二)spring boot 框架整合 thymeleaf

    spring boot 框架整合 thymeleaf spring boot 的官方文档中建议开发者使用模板引擎,避免使用 JSP.因为若一定要使用 JSP 将无法使用. 注意:本文主要参考学习了大神 ...

  6. Spring Boot实战二:集成Mybatis

    Spring Boot集成Mybatis非常简单,在之前搭建好的项目中加入Mybatis依赖的jar,在配置文件中加入数据库配置即可,如下图所示: 创建对应的Controller.Service.Da ...

  7. Spring boot 入门二:Spring Boot配置文件详解

    一.自定义属性 当我们创建一个springboot项目的时候,系统默认会为我们在src/main/java/resources目录下创建一个application.properties.同时也支持ym ...

  8. Spring学习(十二)-----Spring @PostConstruct和@PreDestroy实例

    实现 初始化方法和销毁方法3种方式: 实现标识接口 InitializingBean,DisposableBean(不推荐使用,耦合性太高) 设置bean属性 Init-method destroy- ...

  9. Spring学习(十二)-----Spring Bean init-method 和 destroy-method实例

    实现 初始化方法和销毁方法3种方式: 实现标识接口 InitializingBean,DisposableBean(不推荐使用,耦合性太高) 设置bean属性 Init-method destroy- ...

  10. spring学习笔记二:spring使用构造方法注入(set方式注入)

    项目目录树: 1.spring的依赖包配置 * SPRING_HOME/dist/spring.jar * SPRING_HOME/lib/log4j/log4j-1.2.14.jar * SPRIN ...

随机推荐

  1. php写入文件fwrite() 函数用法

    在php中,php fwrite() 函数是用于写入文件(可安全用于二进制文件).说的简单点,就是在一个文件中,添加新的内容,本篇文章收集总结了几篇关于php写入文件fwrite() 函数用法的总结, ...

  2. LeetCode 536----Construct Binary Tree from String

    536. Construct Binary Tree from String You need to construct a binary tree from a string consisting ...

  3. Debian 8 升级到 9 Debian 9 How to upgrade Debian 8 Jessie to Debian 9 Stretch

    How to upgrade Debian 8 Jessie to Debian 9 Stretch Contents 1. Objective 2. What's New 3. Preparatio ...

  4. 切换Fragment时实现数据保持

    摘要 Fragment设计初衷是为了简化不同屏幕分辨率的开发难度,他将代表一个功能的UI及其相关数据看做一个模块,以便达到复用.可以将Fragment看作是一个可以嵌入布局中的activity,有自己 ...

  5. 强网杯2018 pwn复现

    前言 本文对强网杯 中除了 2 个内核题以外的 6 个 pwn 题的利用方式进行记录.题目真心不错 程序和 exp: https://gitee.com/hac425/blog_data/blob/m ...

  6. needPrint 不显示打印按钮

     客户问题:       客户用的是needPrint 来显示打印按钮,现在访问不能显示后台提示有错误 打开控制台显示: java.security.AccessControlException: ...

  7. Java类的封装

    java中四种不同的限定词限定的成员(成员变量或成员变量方法),访问权限由大到小依次为: public(公共的) 可以被所有的类访问 protected(受保护的) 可以被这个类本身访问 可以被它的子 ...

  8. Linux 环境下为VirtualBox安装增强功能

    VirtualBox安装CentOS后,再安装增强功能就可以共享文件夹.粘贴板以及鼠标无缝移动,主要步骤如下: 1.yum -y update 2.yum -y install g++ gcc gcc ...

  9. iostat 工具分析I/O性能

    iostat命令用途:主要用于监控系统设备的IO负载情况,iostat首次运行时显示自系统启动开始的各项统计信息,之后运行iostat将显示自上次运行该命令以后的统计信息.用户可以通过指定统计的次数和 ...

  10. Vue2学习笔记:数据交互vue-resource

    基本语法 必须引入一个库:vue-resource github地址 // 基于全局Vue对象使用http Vue.http.get('/someUrl', [options]).then(succe ...