MyBatis系列(五)——Spring整合MyBatis

前言

SSM框架是比较经典成熟的架构设计,MyBatis作为持久层框架只有融入到Spring框架中才能更好地发挥它的作用,简化开发人员的工作。本篇文章将对SSM整合MyBatis的步骤进行讲解,希望对各位读者有所帮助。

想要了解更多MyBaits系列文章,可以从下面的传送门阅读:

MyBatis系列(一)——MyBatis的介绍和CRUD
MyBatis系列(二)——MyBatis的动态代理和映射文件动态配置
MyBatis系列(三)——MyBatis的类型处理器和PageHelper分页插件
MyBatis系列(四 )——MyBatis的多表操作
MyBatis系列(六)——MyBatis的注解开发


一、简单整合MyBatis框架

简单整合和完全整合的版本主要区别在于MyBatis是否交由Spring进行管理,前者的话MyBatis只是作为持久层框架,并没有和spring进行交互。我们来看一下怎么实现吧。

1、 创建一个web项目的maven工程

这个步骤的话可以参考这篇文章或者自行百度:使用IDEA创建Maven的web项目

2、配置MyBatis核心配置文件

resources根目录下创建sqlMapConfig.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>
    <!-- 引入jdbc.properties -->
    <properties resource="jdbc.properties"></properties>

    <!--定义别名-->
    <typeAliases>
        <typeAlias type="com.qiqv.pojo.User" alias="user"></typeAlias>
    </typeAliases>

    <!-- 配置环境 -->
    <environments default="devlopment">
        <environment id="devlopment">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 引入mapper映射文件 -->
    <mappers>
        <mapper resource="com/qiqv/mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>

resources根目录下创建jdbc.properties数据源文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

resources根目录下创建创建存放映射文件的新目录后,新建映射文件UserMapper.xml

<?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="com.qiqv.mapper.UserMapper">

    <select id="getAllUsers" resultType="user">
        select * from user;
    </select>
</mapper>
3、配置spring-mvc相关配置
(1)配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Archetype Created Web Application</display-name>

  <!-- 配置初始化参数: spring核心配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 启动监听器,将applicationContext上下文对象放到全局作用域中 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 配置乱码控制器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

这里的话要清楚为啥要配置这些东西,ContextLoaderListener是为了项目启动的时候将applicationContext上下文对象放到项目的域中,DispatcherServlet 的配置是注册前端控制器,这样springmvc才能发挥抽取servlet共有部分,简化我们操作的效果,CharacterEncodingFilter也很好理解,就是帮助我们做字符集的编码转换。

(2)在resources根路径下创建spring-mvc配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

    <!--组件扫描  主要扫描controller-->
    <context:component-scan base-package="com.qiqv.controller"></context:component-scan>
    <!--配置mvc注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--内部资源视图解析器-->
    <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--开发静态资源访问权限-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>

主要是开启了包扫描和注解驱动和配置前端控制器等操作

4、在resources根路径下创建applicationContext.xml配置文件
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

    <!--组件扫描 扫描service和mapper-->
    <context:component-scan base-package="com.qiqv">
        <!--排除controller的扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>
</beans>

这里的话很简单,我们只需要配置包扫描即可

5、项目的基础包和类创建
(1)数据库中创建具体的表
(2)pojo类创建
public class User {

    private Integer uid;
    private String username;
    private String password;
    private Date birth;
    //省略get、set方法...
}
(3)controller类创建
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("getAllUsers")
    public ModelAndView getAllUsers() throws Exception{
        List<User> allUsers = userService.getAllUsers();
        ModelAndView mav = new ModelAndView();
        mav.addObject("userList",allUsers);
        mav.setViewName("userList");
        return mav;
    }
}
(4)service类和接口创建
public interface UserService {

    List<User> getAllUsers()  throws Exception;
}
@Service("userService")
public class UserServiceImpl implements UserService{
    @Override
    public List<User> getAllUsers() throws Exception {
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> allUsers = mapper.getAllUsers();
        sqlSession.close();
        return allUsers;
    }
}
(5)mapper接口创建
public interface UserMapper {

    List<User> getAllUsers();
}
(6)页面创建

/webapp/WEB-INF目录下新建page目录,创建userList.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>展示用户数据列表</h1>
    <table border="1">
        <tr>
            <th>用户id</th>
            <th>用户名称</th>
            <th>用户金额</th>
        </tr>

        <c:forEach items="${userList}" var="account">
            <tr>
                <td>${account.uid}</td>
                <td>${account.username}</td>
                <td>${account.password}</td>
            </tr>
        </c:forEach>

    </table>
</body>
</html>

启动项目后,访问http://localhost:8080/user/getAllUsers查看结果

二、SSM完全整合MyBatis框架

从上面简单整合的代码可以看到,MyBatis框架并没有融入到spring框架中,而是作为持久层单独存在,这样的话存在着两个问题:
(1)sqlSessionFactory对象每次都需要自己创建,这部分代码还有进一步简化的空间,比如直接交由spring进行托管,这样以后要使用bean的话只需要使用@Autowired注解注入就行(当然了,这个问题虽然也可以通过工具类解决,但还是没有让spring托管这么方便)
(2)在事务的管理上,也是MyBatis自己实现的,这一部分可以交由spring的申明式事务来管理

基于上面的问题,我们完全整合MyBatis需要改动的地方主要有四处:

1、 添加mybatis-spring的整合依赖
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
2、applicatoinContext.xml文件将sqlMapConfig.xml的文件整合进来
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

    <!--组件扫描 扫描service和mapper-->
    <context:component-scan base-package="com.qiqv">
        <!--排除controller的扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

    <!-- 引入数据源配置 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 给映射的类配置别名 -->
        <!-- 默认的别名是model类的首字母小写 -->
        <property name="typeAliasesPackage" value="com.qiqv.pojo"></property>
        <!-- 配置mybatis核心配置文件的路径 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>

    <!-- 开启mapper接口扫描,spring帮我们生成mapper动态实现类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qiqv.mapper"></property>
    </bean>

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

    <!-- 配置事务增强 -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务的aop织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qiqv.service.*.*(..))"></aop:advisor>
    </aop:config>

</beans>

这里主要多了两类配置,一类是配置spring的申明式事务,这样以后的事务将交由spring进行管理,第二类是mybatis的配置,我们可以将mybatis的相关配置迁移到applicationContext.xml配置文件中。

3、 删除sqlMapConfig.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>


</configuration>

其实这个时候里面基本没有啥配置了,我们甚至都可以不用配置这个文件

4、修改原先service实现类的内容
@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() throws Exception {
        List<User> allUsers = userMapper.getAllUsers();
        return allUsers;
    }
}

回头看之前的代码,现在的代码简直简洁的一笔...

最后,我们再重启一下项目,看一下是否能够成功


至此,有关SSM整合MyBatis的讲解就到此为止了。
想要获取文章中的源代码,可以去我的码云上面下载:https://gitee.com/moutory/mybatis-ssm

在查找资料的过程中,发现有一篇文章对于spring整合mybatis-plus过程中的配置文件讲得比较清楚,这里也附上给大家参考:整合ssm(spring+springmvc+mybatis-plus)

posted @ 2021-04-06 22:51  moutory  阅读(9)  评论(0编辑  收藏  举报  来源