Mybatis与Spring集成的几种方式详解

简介: Mybatis与Spring集成的几种方式详解

MyBatis使用中有两种方式,一种是与其他框架集成,如与Spring集成(项目中大多采用这种方式)。另外一种则是手动获取sqlsession去进行数据操作(测试时会用)。


【1】不与spring集成

即,使用sqlSessionFactory获取sqlSession进行操作。

【2】与spring集成不使用MapperScannerConfigurer


不使用MapperScannerConfigurer,说明需要手动注册dao-Bean或者mapperBean于容器中。Controller或者Service使用方法仍然为调用该bean对应的dao接口方法去进行数据的一系列操作。

集成步骤

  • ① 配置userMapper.xml (普通的增删改查等具体SQL);
  • ② 配置spring.xml(核心配置文件);
  • ③ 配置spring-userMapper.xml(将dao注册到容器中)。



spring.xml如下:

<beans xmln<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:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!-- 数据源配置, 使用 DriverManagerDataSource  -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > 
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
    </bean>
    <!-- mybatis的SQLSession的工厂 :SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
         <!-- 非注解dao,配置如下属性可以使用简单类名 !-->
        <property name="typeAliasesPackage" value="com.web.model">
        </property>
     </bean>
        <!-- 手动导入dao-bean配置文件 -->
    <import resource="config/web/spring/spring-userMapper.xml"/>
    <!-- *************事务管理******************* -->
    <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

配置spring-userMapper.xml (需手动导入到spring.xml)

该文件配置了dao接口对应的bean,spring加载该bean,即可调用对应dao接口的方法进行数据操作。当然也可以直接配置在spring.xml文件中,这里为了显示说明。


如果使用这种方式,那么在模块化开发中,每个dao接口会对应一个如下的配置文件。这样的配置方式将会导致项目中有大量xml文件,所以你可以将dao接口配置的bean集合在一个xml中。


总得来说,建议使用与spring集成2的方式—使用MapperScannerConfigurer。

具体配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    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 
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                           http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
  <!-- 根据dao接口构建的 mapperBean -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        <!--这里为bean对应的dao接口-->
        <property name="mapperInterface"  value="com.web.mapper.UserMapper" />
    </bean>
</beans>

项目中通过dao操作数据的几种情况

第一种情况

com.web.mapper.UserMapper 使用了注解,接口上面并未使用@Repository注解,没有使用@Repository注解不能自动扫描,但是因为使用了xml将dao-bean注册到容器,所以可以使用。sql语句注解在抽象方法上面,即注解dao,那么肯定不需要sql xml了啊

第二种情况

IUserMapper.java与IUserMapper.xml(具体的增删改查sql)在同一个文件目录下,框架会自动加载对应的xml


即,dao的方法上没有注解SQL,需要配置对应的xml。


不使用MapperScannerConfigurer时,如果xml与dao接口在同一个目录下,那么框架会自动加载;如果xml与dao不在同一个目录下,则需要将xml手动引入到spring.xml。


第三种情况


为sqlSessionFactory增加属性配置。即,加载类路径下的mybatis.xml(将所有需要加载的“*Mapper.xml”引入到了mybatis.xml,那么spring.xml中只需要引入mybatis.xml即可)。

<property name="configLocation" value="classpath:mybatis.xml"></property>


mybatis.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>
  <properties resource="jdbc.properties"/>
<!--  使全局的映射器启用或禁用缓存-->
  <settings>
    <setting name='cacheEnabled' value='true'/>
  </settings>
  <!-- 配置实体类的别名 -->
  <typeAliases>
    <!-- <typeAlias type="com.web.model.User" alias="User"/> -->
    <package name="com.web.model"/>
  </typeAliases>
<!-- 
  development : 开发模式
  work : 工作模式
 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
      </dataSource>
    </environment>
  </environments>
  <!--这里引入dao-bean接口对应的具体SQL的配置文件-->
  <mappers>
    <mapper resource="com/web/mapperxml/IUserMapper.xml"/>
    <mapper resource="com/web/mapperxml/IGoodsMapper.xml"/>
    <mapper resource="com/web/mapperxml/IOrderMapper.xml"/>
  </mappers>
</configuration>


第四种情况

即,所有的"IUserMapper.xml"都放在了指定路径下(如,com.web.mapperxml),那么如下配置,将会加载该路径下所有的"IUserMapper.xml"文件。


这里每个"IUserMapper.xml"对应一个dao接口中方法对应具体SQL配置。


需要说明的是,如果将数据源等配置在spring.xml中,那么将不会再需要第三种情况中所说的mybatis.xml文件。

<property name="mapperLocations" >
         <list>         
           <value>
           classpath*:com/web/mapperxml/**/*.xml
           </value>
         </list>
</property>

构建bean之后,需加载对应的sqlStatements—xml或者sql注解

使用方式如下:

@Resource(name="userMapper")
private UserMapper userMapper;
userMapper.addUser(user);

可能会觉得比较乱,这里说明如下。


spring-userMapper.xml配置的是dao接口对应的bean;

IUserMapper.xml配置的是dao接口抽象方法对应的具体SQL。

IUserMapper.xml常与dao接口放在一起,这样框架会自动加载(第二种情况);

如果IUserMapper.xml未与dao接口放在一起,那么建议集体放在指定路径下(第四种情况);

spring-userMapper.xml需要手动引入到spring.xml中(如果dao-bean未配置在spring.xml中)。

【3】与spring集成使用MapperScannerConfigurer

不必再使用spring-userMapper.xml, IUserMapper.xml(SQL文件)可是永远少不了的,除非你在Mapper方法上面使用注解SQL。


① spring.xml

<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:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!--使用注解情况下,配置该属性标签,将会自动扫描加载使用了类似注解@Controller、@Service等的bean-->
 <context:component-scan base-package="com"></context:component-scan>
    <!-- 数据源配置, 使用 DriverManagerDataSource  -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > 
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
    </bean>
    <!-- mybatis的SQLSession的工厂 :SqlSessionFactoryBean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 非注解dao,配置该属性可以使用简单类名 !user instead of com.web.model.User -->
        <property name="typeAliasesPackage" value="com.web.model"></property>
        <!--自动扫描加载指定位置的mapper xml(配置具体SQL);
        若xml与接口在同一个包下面,则不需要配置该属性   -->
    <property name="mapperLocations" >
            <list>  <value>classpath*:com/web/mapper/**/*.xml</value>
            </list>
        </property>
    </bean>
    <!-- 
    mybatis自动扫描加载sql映射文件/接口:MapperScannerConfigurer
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
       <!-- 可以考虑使用通配符 * 扫描多个包,Mapper接口上面使用@Repository注解 -->
      <property name="basePackage" value="com.web.mapper" />
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
       <!--注解过滤:如果不配置annotationClass,将扫描basePackage下的所有接口-->
       <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
       <!--如下配置将会只生成IUserMapper对应的dao-bean
       <property name="markerInterface" value="com.web.mapper.IUserMapper" />  -->
    </bean>
    <!-- *************事务管理******************* -->
    <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 注解方式配置事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>


这里说明一下MapperScannerConfigurer的属性 :


basePackage : 扫描的基础包;


sqlSessionFactoryBeanName:上面配置的sqlsessionFactorybean名字;


annotationClass:过滤注解类(与basePackage 是"与"的关系);


markerInterface:过滤接口(与basePackage 是"与"的关系);


需要说明的是annotationClass和markerInterface只能选择其一,且都是具体类,即markerInterface的值不能为com.web.mapper.*。如果使用markerInterface,则失去了MapperScannerConfigurer的意义,故常使用配置如下 :

<!--注解过滤:如果不配置annotationClass,将扫描basePackage下的所有接口-->
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>

注意:通过上述配置,只是不需要spring-userMapper.xml(dao-bean配置文件),IUserMapper.xml文件永远需要(除非你使用注解dao)。


此时项目操作数据情况如下

第一种情况:com.web.mapper.UserMapper 使用了注解,接口上面使用@Repository注解。sql语句在抽象方法上面,这时则不需要IUserMapper.xml映射文件


第二种情况:IUserMapper.java与IUserMapper.xml在同一个文件目录下,框架会自动加载对应的xml


第三种情况:为sqlSessionFactory增加属性

<property name="configLocation" value="classpath:mybatis.xml"></property>


mybatis.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>
  <properties resource="jdbc.properties"/>
<!--  使全局的映射器启用或禁用缓存-->
  <settings>
    <setting name='cacheEnabled' value='true'/>
  </settings>
  <!-- 配置实体类的别名 -->
  <typeAliases>
    <!-- <typeAlias type="com.web.model.User" alias="User"/> -->
    <package name="com.web.model"/>
  </typeAliases>
<!-- 
  development : 开发模式
  work : 工作模式
 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
      </dataSource>
    </environment>
  </environments>
  // 将所有的SQL配置文件引入
  <mappers>
    <mapper resource="com/web/mapperxml/IUserMapper.xml"/>
  </mappers>
</configuration>

第四种情况:为sqlSessionFactory增加属性配置

<property name="mapperLocations" >
    <list>  <value>classpath*:com/web/mapper/**/*.xml</value></list>
</property>

上面四种情况不再赘述,建议使用第四种情况,将所有的"IUserMapper.xml"文件放在指定路径在,然后为sqlSessionFactory配置属性mapperLocations。


【Tips】

如下配置,则只扫描basePackage下有Repository注解的接口:

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.web.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--如果增加一下属性,则只扫描basePackage下有Repository注解的接口-->
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    </bean>

总结不论使用哪种方式,基本点不变:sql语句--注解或者xml;映射器接口注入。通常项目中MyBatis与Spring或者SpringBoot整合时,会使用MapperScannerConfigurer,并将所有的*mapper.xml放在src/main/resources/mapper下面,使用mapperLocations统一扫描。


目录
相关文章
|
9天前
|
Java 数据库连接 数据库
spring复习05,spring整合mybatis,声明式事务
这篇文章详细介绍了如何在Spring框架中整合MyBatis以及如何配置声明式事务。主要内容包括:在Maven项目中添加依赖、创建实体类和Mapper接口、配置MyBatis核心配置文件和映射文件、配置数据源、创建sqlSessionFactory和sqlSessionTemplate、实现Mapper接口、配置声明式事务以及测试使用。此外,还解释了声明式事务的传播行为、隔离级别、只读提示和事务超时期间等概念。
spring复习05,spring整合mybatis,声明式事务
|
12天前
|
Java 数据库连接 数据库
SpringBoot 整合jdbc和mybatis
本文详细介绍了如何在SpringBoot项目中整合JDBC与MyBatis,并提供了具体的配置步骤和示例代码。首先,通过创建用户实体类和数据库表来准备基础环境;接着,配置Maven依赖、数据库连接及属性;最后,分别展示了JDBC与MyBatis的集成方法及其基本操作,包括增删查改等功能的实现。适合初学者快速入门。
SpringBoot 整合jdbc和mybatis
|
4天前
|
存储 前端开发 Java
Spring Boot 集成 MinIO 与 KKFile 实现文件预览功能
本文详细介绍如何在Spring Boot项目中集成MinIO对象存储系统与KKFileView文件预览工具,实现文件上传及在线预览功能。首先搭建MinIO服务器,并在Spring Boot中配置MinIO SDK进行文件管理;接着通过KKFileView提供文件预览服务,最终实现文档管理系统的高效文件处理能力。
|
21天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
8天前
|
XML Java 关系型数据库
springboot 集成 mybatis-plus 代码生成器
本文介绍了如何在Spring Boot项目中集成MyBatis-Plus代码生成器,包括导入相关依赖坐标、配置快速代码生成器以及自定义代码生成器模板的步骤和代码示例,旨在提高开发效率,快速生成Entity、Mapper、Mapper XML、Service、Controller等代码。
springboot 集成 mybatis-plus 代码生成器
|
9天前
|
SQL XML Java
springboot整合mybatis-plus及mybatis-plus分页插件的使用
这篇文章介绍了如何在Spring Boot项目中整合MyBatis-Plus及其分页插件,包括依赖引入、配置文件编写、SQL表创建、Mapper层、Service层、Controller层的创建,以及分页插件的使用和数据展示HTML页面的编写。
springboot整合mybatis-plus及mybatis-plus分页插件的使用
|
9天前
|
XML Java 数据库连接
springboot中整合mybatis及简单使用
这篇文章介绍了如何在Spring Boot项目中整合MyBatis,包括依赖引入、配置数据源、创建测试表、编写Mapper接口和XML文件、以及创建Service和Controller层的步骤。
springboot中整合mybatis及简单使用
|
22天前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
27天前
|
前端开发 JavaScript Java
技术分享:使用Spring Boot3.3与MyBatis-Plus联合实现多层次树结构的异步加载策略
在现代Web开发中,处理多层次树形结构数据是一项常见且重要的任务。这些结构广泛应用于分类管理、组织结构、权限管理等场景。为了提升用户体验和系统性能,采用异步加载策略来动态加载树形结构的各个层级变得尤为重要。本文将详细介绍如何使用Spring Boot3.3与MyBatis-Plus联合实现这一功能。
57 2
|
2月前
|
测试技术 Java Spring
Spring 框架中的测试之道:揭秘单元测试与集成测试的双重保障,你的应用真的安全了吗?
【8月更文挑战第31天】本文以问答形式深入探讨了Spring框架中的测试策略,包括单元测试与集成测试的有效编写方法,及其对提升代码质量和可靠性的重要性。通过具体示例,展示了如何使用`@MockBean`、`@SpringBootTest`等注解来进行服务和控制器的测试,同时介绍了Spring Boot提供的测试工具,如`@DataJpaTest`,以简化数据库测试流程。合理运用这些测试策略和工具,将助力开发者构建更为稳健的软件系统。
39 0
下一篇
无影云桌面