2022-08-20

本文讲解使用Maven单模块方式进行Spring MVC+Spring+MyBatis整合。为了把整合步骤体现地更加清晰,我们可以把步骤分为以下六个部分:

  1. 准备数据库环境
  2. 单独搭建Spring环境
  3. 单独搭建Spring MVC环境
  4. Spring整合Spring MVC
  5. 单独搭建MyBatis环境
  6. MyBatis整合Spring

1 准备数据库环境

1.1 创建ssm数据库

202202131335092501.png

1.2 建立测试表

            
            CREATE TABLE `user` (
               `id` int(11) NOT NULL AUTO_INCREMENT,
               `username` varchar(32) NOT NULL COMMENT '用户名称',
               `birthday` datetime DEFAULT NULL COMMENT '生日',
               `sex` char(1) DEFAULT NULL COMMENT '性别',
               `address` varchar(256) DEFAULT NULL COMMENT '地址',
               PRIMARY KEY (`id`)
             ) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8

1.3 插入测试数据

202202131335099002.png

2 单独搭建Spring环境

2.1 创建Web项目

202202131335105553.png

2.2 导入SSM相关依赖

            
            <?xml version="1.0" encoding="UTF-8"?>
            
            <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
              <modelVersion>4.0.0</modelVersion>  
              <groupId>com.yiidian</groupId>  
              <artifactId>ch04_04_springmvc_ssm</artifactId>  
              <version>1.0-SNAPSHOT</version>  
              <packaging>war</packaging>
              <!--
                 SSM整合的基础依赖
               -->
              <!-- 1.spring相关的依赖 -->
              <dependencies>
                <!-- 1.1 ioc -->
                <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-context</artifactId>
                  <version>5.0.2.RELEASE</version>
                </dependency>
                <!--1.2 aop -->
                <dependency>
                  <groupId>org.aspectj</groupId>
                  <artifactId>aspectjweaver</artifactId>
                  <version>1.8.7</version>
                </dependency>
                <!-- 1.3 声明式事务-->
                <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-tx</artifactId>
                  <version>5.0.2.RELEASE</version>
                </dependency>
                <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-jdbc</artifactId>
                  <version>5.0.2.RELEASE</version>
                </dependency>
                <!-- 1.4 test -->
                <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-test</artifactId>
                  <version>5.0.2.RELEASE</version>
                </dependency>
                <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>4.12</version>
                </dependency>
            
            
                <!-- 2. mybatis相关依赖 -->
                <!-- 2.1 mysql驱动-->
                <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>5.1.46</version>
                </dependency>
                <!-- 2.2 数据源 -->
                <dependency>
                  <groupId>com.alibaba</groupId>
                  <artifactId>druid</artifactId>
                  <version>1.1.6</version>
                </dependency>
                <!-- 2.3 mybatis核心包 -->
                <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis</artifactId>
                  <version>3.4.5</version>
                </dependency>
            
                <!-- 3. springmvc相关依赖-->
                <!-- 3.1 springmvc核心包 -->
                <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-webmvc</artifactId>
                  <version>5.0.2.RELEASE</version>
                </dependency>
                <!--3.2 servlet依赖 -->
                <dependency>
                  <groupId>javax.servlet</groupId>
                  <artifactId>servlet-api</artifactId>
                  <version>2.5</version>
                </dependency>
                <!--3.3 jstl标签库-->
                <dependency>
                  <groupId>jstl</groupId>
                  <artifactId>jstl</artifactId>
                  <version>1.2</version>
                </dependency>
            
                <!-- 4. log4j日志 -->
                <dependency>
                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                  <version>1.2.17</version>
                </dependency>
            
                <!-- 5. spring与mybatis整合包 *** -->
                <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis-spring</artifactId>
                  <version>1.3.1</version>
                </dependency>
              </dependencies>
            </project>

2.3 设计Pojo

            
            package com.yiidian.domain;
            
            import java.util.Date;
            
            /**
             * 实体类
             * 一点教程网 - www.yiidian.com
             */
            public class User {
                private Integer id;
                private String username;
                private Date birthday;
                private String sex;
                private String address;
            
                public Integer getId() {
                    return id;
                }
            
                public void setId(Integer id) {
                    this.id = id;
                }
            
                public String getUsername() {
                    return username;
                }
            
                public void setUsername(String username) {
                    this.username = username;
                }
            
                public Date getBirthday() {
                    return birthday;
                }
            
                public void setBirthday(Date birthday) {
                    this.birthday = birthday;
                }
            
                public String getSex() {
                    return sex;
                }
            
                public void setSex(String sex) {
                    this.sex = sex;
                }
            
                public String getAddress() {
                    return address;
                }
            
                public void setAddress(String address) {
                    this.address = address;
                }
            
                @Override
                public String toString() {
                    return "User{" +
                            "id=" + id +
                            ", username='" + username + '\'' +
                            ", birthday=" + birthday +
                            ", sex='" + sex + '\'' +
                            ", address='" + address + '\'' +
                            '}';
                }
            }

2.3 编写业务接口和实现

UserService接口:

            
            package com.yiidian.service;
            import com.yiidian.domain.User;
            import java.util.List;
            /**
             * 业务层接口
             * 一点教程网 - www.yiidian.com
             */
            public interface UserService {
                /**
                 * 查询所有用户
                 */
                public List<User> findAll();
            }

UserService实现类:

            
            package com.yiidian.service.impl;
            import com.yiidian.domain.User;
            import com.yiidian.service.UserService;
            import org.springframework.stereotype.Service;
            
            import java.util.List;
            
            /**
             *业务层实现类
             * 一点教程网 - www.yiidian.com
             */
            @Service
            public class UserServiceImpl implements UserService{
                @Override
                public List<User> findAll() {
                    System.out.println("查询所有用户...");
                    return null;
                }
            }

这里给业务实现类加入@Service注解,目的是把该对象放入Spring IOC容器。

2.4 编写Spring配置

202202131335111434.png

内容如下:

            
            <?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">
            
                <!--扫描Service实现类-->
                <context:component-scan base-package="com.yiidian.service"/>
            </beans>

2.5 编写Spring环境测试类

202202131335116175.png

内容如下:

            
            package com.yiidian.test;
            
            import com.yiidian.service.UserService;
            import org.junit.Test;
            import org.junit.runner.RunWith;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.test.context.ContextConfiguration;
            import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
            /**
             * 单独测试Spring环境是否OK
             * 一点教程网 - www.yiidian.com
             */
            @RunWith(SpringJUnit4ClassRunner.class) // 加载Spring环境
            @ContextConfiguration("classpath:applicationContext.xml") //读取spring配置,创建IOC容器
            public class TestSpring {
                //注入service对象
                @Autowired
                private UserService userService;
            
                @Test
                public void testFindAll(){
                    userService.findAll();
                }
            }

2.6 运行测试类

202202131335121396.png

3 单独搭建Spring MVC环境

3.1 Spring MVC核心控制器

            
            <?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"
            	version="2.5">
            	
            	<!-- 配置核心控制器 -->
            	<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:springmvc.xml</param-value>
            		</init-param>
            		<load-on-startup>1</load-on-startup>
            	</servlet>
            	<servlet-mapping>
            		<servlet-name>dispatcherServlet</servlet-name>
            		<url-pattern>/</url-pattern>
            	</servlet-mapping>
            </web-app>

3.2 springmvc.xml配置

202202131335127487.png

内容如下:

            
            <?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"
                   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">
               
                <!-- 1.扫描控制器 -->
                <context:component-scan base-package="com.yiidian.controller"/>
            
                <!-- 2.视图解析器 -->
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/pages/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            
                <!-- 3.创建处理器映射器和处理器适配器 -->
                <mvc:annotation-driven/>
            </beans>

3.3 编写UserController

            
            package com.yiidian.controller;
            
            import org.springframework.stereotype.Controller;
            import org.springframework.ui.Model;
            import org.springframework.web.bind.annotation.RequestMapping;
            
            /**
             * 控制器
             * 一点教程网 - www.yiidian.com
             */
            @Controller
            @RequestMapping("/user")
            public class UserController {
                /**
                 * 查询所有用户
                 */
                @RequestMapping("/list")
                public String list(Model model){
                    //存入数据到request域
                    model.addAttribute("list","用户数据");
                    //返回list.jsp页面
                    return "list";
                }
            }

3.4 编写list.jsp,显示数据

202202131335132478.png

内容如下:

            
            <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>一点教程网-显示用户数据</title>
            </head>
            <body>
            ${list}
            </body>
            </html>

3.5 项目部署到Tomcat

访问Controller:http://localhost:8080/user/list,显示效果如下:

202202131335137479.png

4 Spring整合Spring MVC

4.1 配置Spring监听器

Spring和Spring MVC融合使用,非常简单,只要在web.xml配置监听器,在项目启动的时候,加载applicationContext.xml文件,把Spring环境启动即可。

            
            <!-- 配置spring监听器,用于加载applicationContext.xml(初始化SpringIOC容器) -->
            <context-param>
            	<param-name>contextConfigLocation</param-name>
            	<param-value>classpath:applicationContext.xml</param-value>
            </context-param>

4.2 在控制层调用业务层

            
            package com.yiidian.controller;
            
            import com.yiidian.service.UserService;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.stereotype.Controller;
            import org.springframework.ui.Model;
            import org.springframework.web.bind.annotation.RequestMapping;
            
            /**
             * 控制器
             * 一点教程网 - www.yiidian.com
             */
            @Controller
            @RequestMapping("/user")
            public class UserController {
                @Autowired
                private UserService userService;
                
                /**
                 * 查询所有用户
                 */
                @RequestMapping("/list")
                public String list(Model model){
                    //调用业务层方法
                    userService.findAll();
                    
                    //存入数据到request域
                    model.addAttribute("list","用户数据");
                    //返回list.jsp页面
                    return "list";
                }
            }

如果Controller成功注入Service,代表Spring与Spring MVC整合成功!

4.3 测试

2022021313351428810.png

5 单独搭建MyBatis环境

5.1 编写UserDao接口

            
            package com.yiidian.dao;
            import com.yiidian.domain.User;
            import org.apache.ibatis.annotations.Select;
            
            import java.util.List;
            
            /**
             * Dao接口
             */
            public interface UserDao {
                /**
                 * 查询所有账户
                 */
                @Select("select * from user")
                public List<User> findAll();
            }

5.2 编写SqlMapConfig.xml

该文件是MyBatis核心配置,里面配置数据源及Dao接口映射等信息。

2022021313351497511.png

内容如下:

            
            <?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"/>
            
                <!--1.别名扫描 -->
                <typeAliases>
                    <package name="com.yiidian.domain"/>
                </typeAliases>
            
                <!--2.数据库连接 -->
                <environments default="mysql">
                    <environment id="mysql">
                        <transactionManager type="jdbc"></transactionManager>
                        <dataSource type="pooled">
                            <property name="url" value="${jdbc.url}"/>
                            <property name="driver" value="${jdbc.driver}"/>
                            <property name="username" value="${jdbc.username}"/>
                            <property name="password" value="${jdbc.password}"/>
                        </dataSource>
                    </environment>
                </environments>
            
                <!--3.映射关联 -->
                <mappers>
                    <package name="com.yiidian.dao"/>
                </mappers>
            
            </configuration>

jdbc.properties:

2022021313351544612.png

内容如下:

            
            jdbc.driver=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8
            jdbc.username=root
            jdbc.password=root
            jdbc.initialSize=3
            jdbc.maxActive=10

5.3 编写MyBatis测试类

2022021313351593013.png

内容如下:

            
            package com.yiidian.test;
            
            import com.yiidian.dao.UserDao;
            import com.yiidian.domain.User;
            import org.apache.ibatis.io.Resources;
            import org.apache.ibatis.session.SqlSession;
            import org.apache.ibatis.session.SqlSessionFactory;
            import org.apache.ibatis.session.SqlSessionFactoryBuilder;
            import org.junit.Test;
            
            import java.io.IOException;
            import java.io.InputStream;
            import java.util.List;
            
            /**
             * 单独测试MyBatis环境是否OK
             *一点教程网 - www.yiidian.com
             */
            public class TestMyBatis {
                @Test
                public void testFindAll() throws IOException {
            
                    //1.加载SqlMapConfig.xml
                    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            
                    //2.创建SqlSessionFactory
                    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                    SqlSessionFactory factory = builder.build(in);
            
                    //3.创建SqlSession
                    SqlSession sqlSession = factory.openSession();
            
                    //4.创建Dao代理对象
                    UserDao accountDao = sqlSession.getMapper(UserDao.class);
            
                    //5.执行方法
                    List<User> list = accountDao.findAll();
                    System.out.println(list);
            
                    //6.释放资源
                    sqlSession.close();
                    in.close();
            
                }
            }

5.4 运行测试类

2022021313351635814.png

6 MyBatis整合Spring

MyBatis整合Spring是SSM整合最关键的一步!毕竟MyBatis和Spring是两个不同框架。整合的思路是:Spring依赖IOC容器创建MyBatis所需要的SqlSessionFactory,从利用SqlSessionFactory完成Dao层的操作。我们来具体步骤:

6.1 MyBatis整合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"
                   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">
            
                <!--扫描Service实现类-->
                <context:component-scan base-package="com.yiidian.service"/>
            
                <!-- 1. 创建数据源 -->
                <context:property-placeholder location="classpath:jdbc.properties"/>
                
                <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                    <property name="url" value="${jdbc.url}"/>
                    <property name="driverClassName" value="${jdbc.driver}"/>
                    <property name="username" value="${jdbc.username}"/>
                    <property name="password" value="${jdbc.password}"/>
                </bean>
            
                <!-- 2. 为了创建Dao代理对象,先创建SqlSessionFactory对象 -->
                <!--  SqlSessionFactoryBean: 创建SqlSessionFactory对象的工具 -->
                <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                    <!-- 注入数据源 -->
                    <property name="dataSource" ref="dataSource"/>
                </bean>
            
                <!-- 3. 扫描Dao接口所在包,扫描后用于创建Dao代理对象,把代理对象放入IOC容器 -->
                <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                    <!-- Dao扫描目录 -->
                    <property name="basePackage" value="com.yiidian.dao"/>
                </bean>
            </beans>

因为Spring已经把之前MyBatis的数据源及Dao映射等信息都集成了,所以MyBatis的SqlMapConfig.xml已经不需要啦,可以删除。

2022021313351698915.png

6.2 业务层注入持久层对象

上面的配置已经成功地让MyBatis和Spring完成整合。接着,我们可以在Service层注入Dao对象,调用其方法:

            
            package com.yiidian.service.impl;
            import com.yiidian.dao.UserDao;
            import com.yiidian.domain.User;
            import com.yiidian.service.UserService;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.stereotype.Service;
            import java.util.List;
            
            /**
             *业务层实现类
             * 一点教程网 - www.yiidian.com
             */
            @Service
            public class UserServiceImpl implements UserService{
                //注入Dao对象
                @Autowired
                private UserDao userDao;
                @Override
                public List<User> findAll() {
                    return userDao.findAll();
                }
            }

6.3 编写测试类

2022021313351770616.png

内容如下:

            
            package com.yiidian.test;
            
            import com.yiidian.service.UserService;
            import org.junit.Test;
            import org.junit.runner.RunWith;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.test.context.ContextConfiguration;
            import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
            
            /**
             * 测试Spring与MyBatis环境是否OK
             * 一点教程网 - www.yiidian.com
             */
            @RunWith(SpringJUnit4ClassRunner.class)
            @ContextConfiguration(value = "classpath:applicationContext.xml")
            public class TestSpringMyBatis {
            
                //从IOC容器中获取业务实现
                @Autowired
                private UserService userService;
            
                @Test
                public void testFindAll(){
                    System.out.println( userService.findAll());
                }
            
            }

6.4 运行测试

2022021313351823417.png

至此,SSM框架已经整合完成。剩下就是把数据显示到JSP页面上。

6.5 修改UserController类

            
            package com.yiidian.controller;
            
            import com.yiidian.domain.User;
            import com.yiidian.service.UserService;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.stereotype.Controller;
            import org.springframework.ui.Model;
            import org.springframework.web.bind.annotation.RequestMapping;
            
            import java.util.List;
            
            /**
             * 控制器
             * 一点教程网 - www.yiidian.com
             */
            @Controller
            @RequestMapping("/user")
            public class UserController {
                @Autowired
                private UserService userService;
            
                /**
                 * 查询所有用户
                 */
                @RequestMapping("/list")
                public String list(Model model){
                    //调用业务层方法
                    List<User> list = userService.findAll();
            
                    //存入数据到request域
                    model.addAttribute("list",list);
                    //返回list.jsp页面
                    return "list";
                }
            }

6.6 修改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>
            </head>
            <body>
            <h3>用户列表</h3>
            | 编号|用户名|生日|性别|地址|
        | :-----: | :-----: | :-----: | :-----: | :-----: | 
        | 编号 | 用户名 | 生日 | 性别 | 地址 | 
        | ${user.id} | ${user.username} | ${user.birthday} | ${user.sex} | ${user.address} | 
        
            </body>
            </html>

6.7 最终显示效果如下

2022021313351880118.png

源码下载:https://pan.baidu.com/s/1BB4_qVMpIiWzEm-aMleJ0Q

阅读全文