(Spring-SpringMVC-MyBatis)超详细SSM整合环境搭建

前言

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。

Spring
  Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
  Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地`new`一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
  SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
  mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。

页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据。

前期准备

整合

  1. 创建基于Maven管理的Web项目。
    默认本地的JDK环境,这里选择Create from archetype 使用Web骨架,点击Next
    在这里插入图片描述
  2. 给项目起个名字,我这里就叫ssm_superb,点击下一步继续

在这里插入图片描述

  1. 这里一定要使用本地的Maven仓库!!!

在这里插入图片描述

  1. 创建完成,发现目录结构并不是完整的(缺少java目录和Resource目录以及测试部分),我们手动补充即可

在这里插入图片描述

  1. 选中src,右键之后一次选择new,Directory。
    在这里插入图片描述
  2. 不得不说现在的idea真的贴心(手动狗头),我们缺少的目录结构,都在提示中,按住Shift全部选中即可添加所有目录。

在这里插入图片描述

  1. 到此,前期工作基本完成
    在这里插入图片描述
  2. 首先引入项目所需要的依赖。pom.xml

其中junit包的版本一定要是4.12及以上,切记!血的教训http://blog.csdn.net/weixin_46002478/article/details/108630322

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <!--统一spring版本-->
        <spring.verison>5.2.8.RELEASE</spring.verison>
    </properties>

    <dependencies>
        <!--spring web核心依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.verison}</version>
        </dependency>
        <!--spring jdbc依赖 用于事务配置-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.verison}</version>
        </dependency>
        <!--spring 测试包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.verison}</version>
        </dependency>
        <!--mysql 驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--druid 阿里连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--mybatis 持久层框架-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--mybatis spring 整合包 现在都有mybatis提供-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <!--json 解析json数据包-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>
        <!--junit 测试包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 创建Package
    在这里插入图片描述
    创建数据库连接配置properties
    在这里插入图片描述

  2. 创建Spring以及SpringMVC配置文件
    application.xml
    spring-mvc.xml
    在这里插入图片描述

  3. 接下来就是配置各种xml时间
    web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--  指定错误显示页面-->
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/error/500.jsp</location>
    </error-page>

    <!--  加载Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <!--  监听器-->
    <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>
        <!--    加载spring mvc配置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd
                           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--    开启注解扫描 关闭默认扫描方式-->
    <context:component-scan base-package="com.superb" use-default-filters="false">
        <!--        只扫描Controller层 因为spring mvc只负责Controller层-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--    配置视图解析器 方便前后端跳转-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--        前缀-->
        <property name="prefix" value="/WEB-INF/"/>
        <!--        后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--    开启mvc注解扫描的支持-->
    <mvc:annotation-driven/>
</beans>

application.xml

<?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.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    开启注解扫描-->
    <context:component-scan base-package="com.superb">
        <!--        不扫描Controller 各司其职-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--    引入外部properties资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--    整合MyBatis-->
    <!--    引入数据源 使用德鲁伊数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--    配置mybatis工厂Bean-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--        数据源填充-->
        <property name="dataSource" ref="dataSource"/>
        <!--        指定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--        指定mapper文件 *.xml 指定所有xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--    将mapper接口添加到spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--        指定mapper接口所在包 自动扫描-->
        <property name="basePackage" value="com.superb.mapper"/>
    </bean>

    <!--    配置事务(目前非必要)-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--        传入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>

</beans>

数据库方面
在这里插入图片描述

配置完成
接下来编写实体类以及mapper接口进行测试(当然也可以选择MyBatis逆向工程)

package com.mybatis.bean;
/**
 * @author Superb
 * @date 2020/9/11 - 15:11
 * @E_mail superb12580@163.com
 */
public class Employee {
    private Integer empId;

    private String empName;
    
    private Integer d_id;

	//set()get()及toString方法已省略
}

Mapper接口

package com.mybatis.mapper;

import com.mybatis.bean.Employee;
import org.apache.ibatis.annotations.*;
import java.util.List;

/**
 * @author Superb
 * @date 2020/9/11 - 15:09
 * @E_mail superb12580@163.com
 */
public interface EmployeeMapper {
    /**
     * 查询所有员工
     * @return
     */
    List<Employee> getEmps();
    
    /**
     * 查询单个员工
     * @param id
     * @return
     */
    Employee getEmp(int id);
}

mapper.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.superb.mapper.EmployeeMapper">

    <resultMap id="empMap" type="com.superb.entity.Employee">
        <id property="empId" column="emp_id"/>
        <result column="emp_name" property="empName"/>
        <result column="d_id" property="dId"/>
    </resultMap>
    
    <select id="getEmp" parameterType="java.lang.Integer" resultMap="empMap">
        select * from emp where emp_id = #{empId}
    </select>

    <select id="getEmps" resultMap="empMap">
        select * from emp
    </select>
</mapper>

生成测试 选中Mapper接口类 快捷键 ctrl+shift+t 生成测试代码
在这里插入图片描述
将两个测试方法全部勾选
在这里插入图片描述
生成如下
在这里插入图片描述
添加测试环境

package com.superb.mapper;

import com.superb.entity.Employee;
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.SpringRunner;

import java.util.List;

import static org.junit.Assert.*;

/**
 * @author Superb
 * @date 2020/9/17 - 16:28
 * @E_mail superb12580@163.com
 */
@RunWith(SpringRunner.class)
@ContextConfiguration({"classpath:application.xml"})
public class EmployeeMapperTest {

    @Autowired
    private EmployeeMapper mapper;
    @Test
    public void getEmp() {
        Employee emp = mapper.getEmp(1);
        System.out.println(emp);
    }

    @Test
    public void getEmps() {
        List<Employee> emps = mapper.getEmps();
        for (Employee e : emps){
            System.out.println(e);
        }
    }
}

进行测试

Employee{empId=1, empName='卢本伟', dId=5}
Employee{empId=1, empName='卢本伟', dId=5}
Employee{empId=2, empName='大司马', dId=2}
Employee{empId=3, empName='Uzi', dId=1}
Employee{empId=4, empName='PDD', dId=2}
Employee{empId=5, empName='茄子', dId=3}
Employee{empId=6, empName='药水哥', dId=5}
Employee{empId=7, empName='旭旭宝宝', dId=4}
Employee{empId=8, empName='小智', dId=5}
Employee{empId=9, empName='化腾', dId=4}

后端测试成功!
配置tomcat服务器
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

编辑Controller层
返回Json数据给前端

package com.superb.controller;

import com.superb.entity.Employee;
import com.superb.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Superb
 * @date 2020/9/12 - 17:47
 * @E_mail superb12580@163.com
 */
@RestController
public class EmpController {

    @Autowired
    private EmployeeMapper mapper;

    @RequestMapping("/emp")
    public List<Employee> getEmp(){
        return mapper.getEmps();
    }
}

点击运行服务器
访问http://localhost:8080/ssm_superb/emp
在这里插入图片描述
完成

Mybatis基于注解方式的一对多、多对一关系映射
https://blog.csdn.net/weixin_46002478/article/details/108539325

Mybatis基于XML方式的一对多、多对一关系映射
https://blog.csdn.net/weixin_46002478/article/details/108545775

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值