7.MyBatis如何无缝对接Spring

1.为什么会出现MyBatis-Spring

Spring框架与MyBatis框架是Java互联网技术的主流框架。但是如何将MyBatis无缝整合到Spring框架中呢?这时候就诞生了MyBatis-Spring。使用这个类库中得类,Spring将会加载必要的MyBatis工厂类和session类。

Spring3.0也仅仅支持ibatis2.0。本来将MyBatis3的支持添加到Spring3.0中。而不幸,Spring3.0的开发在MyBatis3.0官方发布前就结束了。因为Spring开发团队不想发布一个非发布版的MyBatis的整合支持。就放弃了对MyBatis的支持。

随着Spring越来越成为java事实标准的技术框架。Spring 4.0 移除了对iBatis的直接支持。MyBatis团队开发出来了基于Spring的MyBatis整合Jar---MyBatis-Spring。

2.使用MyBatis-Spring的好处

  • 1.使得业务层和模型层得到更好的分离。再Spring框架中MyBatis也更加简单,节约不少的代码
  • 2.甚至不需要显示的使用SqlSessionFactory、SqlSessiond等对象

3.MyBatis-Spring组成部分

  • 1.配置数据源
  • 2.配置SqlSessionFactory
  • 3.配置SqlSessionTemplate
  • 4.配置Mapper
  • 5.事务处理

MyBatis中要构建SqlSessionFactory对象,让它产生SqlSession,而在MyBatis-Spring项目中SqlSession的使用是通过SqlSessionTemplate来实现的,它提供了对SqlSession操作的封装。所以可以通过SqlSessionTemplate可以得到Mapper。

4.在Spring MVC中配置

4.1 配置SqlSessionFactoryBean

在基本的 MyBatis中,session工厂可以使用SqlSessionFactoryBuilder 来创建。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来替代。

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

注意点

  • SqlSessionFactory 有一个单独的必须属性,就是 JDBC 的 DataSource

在SqlSessionFactoryBean的返回getObject的时候,有个验证。

  @Override
  public SqlSessionFactory getObject() throws Exception {
    if (this.sqlSessionFactory == null) {
      afterPropertiesSet();
    }

    return this.sqlSessionFactory;
  }
  @Override
  public void afterPropertiesSet() throws Exception {
    notNull(dataSource, "Property 'dataSource' is required");
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
              "Property 'configuration' and 'configLocation' can not specified with together");

    this.sqlSessionFactory = buildSqlSessionFactory();
  }

4.2配置datasource

这里我们使用的是阿里巴巴的数据库连接池。https://github.com/alibaba/druid

compile group: 'com.alibaba', name: 'druid', version: '1.1.2'
<!--阿里巴巴的数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <!-- 基本属性 url、user、password -->
    <property name="url" value="${jdbc_url}"/>
    <property name="username" value="${jdbc_user}"/>
    <property name="password" value="${jdbc_password}"/>
</bean>

4.3配置数据库链接属性

在resource目录下创建properties文件夹,并创建datasource.properties

jdbc_url=jdbc:mysql://localhost:3306/cnblogs?serverTimezone=Asia/Shanghai&characterEncoding=utf8
jdbc_user=root
jdbc_password=root

使用阿里巴巴的数据库连接池是无需配置数据库驱动。是根据url的前缀来判断的

4.4配置Spring加载配置属性及配置替换动态标签

<!--加载配置文件路径-->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:properties/datasource.properties"></property>
</bean>

<!--获取配置属性之后动态替换标签-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties"/>
</bean>

4.5配置Spring自动创建Mapper接口的bean

MyBatis-Spring提供了一个转换器MapperScannerConfigurer,可以将映射接口转换为Spring容器中Bean。这样就可以在代码中注入映射的bean

<!--采用自动扫描方式创建Mapper Bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.cnblogs.dao"></property>
</bean>

basePackage属性是让你为映射器接口文件设置基本的包路径。 你可以使用分号或逗号作为分隔符设置多于一个的包路径。每个映射器将会在指定的包路径中递归地被搜索到。

4.6配置事务

MyBatis和Spring结合后是使用Spring AOP去管理事务的,使用Spring AOP是相当的简单的,它分为声明式事务和编程性事务。大部分场景下使用声明式事务就可以了。

  • 引入Jar包
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!--使用声明式事务管理方式-->
<tx:annotation-driven transaction-manager="transactionManager"/>

5.完整的Spring xml配置及引用的Jar包

  • 引入的Jar列表
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.1'
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.5'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile group: 'com.alibaba', name: 'druid', version: '1.1.2'
  • 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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       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
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--spring可以自动去扫描base-pack下面的包或者子包下面的Java文件-->
    <context:component-scan base-package="com.cnblogs.controller,com.cnblogs.service,com.cnblogs.dao"/>

    <!--自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdpter-->
    <mvc:annotation-driven/>

    <!-- 对静态资源文件的访问-->
    <mvc:default-servlet-handler/>

    <!--加载配置文件路径-->
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:properties/datasource.properties"></property>
    </bean>

    <!--获取配置属性之后动态替换标签-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties"/>
    </bean>

    <!--阿里巴巴的数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_user}"/>
        <property name="password" value="${jdbc_password}"/>
    </bean>

    <!--构建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
    </bean>

    <!--采用自动扫描方式创建Mapper Bean-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cnblogs.dao"></property>
    </bean>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--使用声明式事务管理方式-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/content"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,861评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,273评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,005评论 6 342
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,022评论 0 2
  • 年少时我们都曾有过太多的想象,总觉得生活如同自己在武侠小说里看到的那样,成年之后可以快意恩仇,可以做乔峰 令狐冲 ...
    孙道强阅读 1,119评论 0 1