SSM框架整合


SSM框架整合

  • Spring MVC 负责实现 MVC 设计模式

  • MyBatis 负责数据持久层

  • Spring负责管理SpringMVC和MyBatis所用到的相关对象的创建和依赖注入

    SSM框架整合,实际上是Spring与MyBatis的整合,因为SpringMVC是Spring的一个子模块

1.1 整合环境

  • IDEA 2021.2.3 Ultimate Edition
  • MySQL 8.0.26
  • Tomcat 10.0.11
  • Maven 3.8.3

1.2 基础环境搭建

  • 创建maven工程
  • 引入项目依赖的jar包
  • 引入bootstrap前端框架

1.3 配置文件*

  • 第一步:pom.xml 引入依赖jar包

        
            
            
                org.springframework
                spring-webmvc
                5.2.18.RELEASE
            
    
            
            
                org.springframework
                spring-jdbc
                5.2.18.RELEASE
            
    
            
            
                org.springframework
                spring-aop
                5.2.18.RELEASE
            
            
                org.springframework
                spring-aspects
                5.2.18.RELEASE
            
    
            
            
                org.springframework
                spring-test
                5.2.18.RELEASE
            
    
            
            
                org.mybatis
                mybatis
                3.5.7
            
    
            
            
                org.mybatis.generator
                mybatis-generator-core
                1.3.7
            
    
            
            
                org.mybatis
                mybatis-spring
                1.3.1
            
    
            
            
                mysql
                mysql-connector-java
                8.0.26
            
    
            
            
                com.alibaba
                druid
                1.2.6
            
    
            
            
                com.github.pagehelper
                pagehelper
                5.3.0
            
    
            
            
                jstl
                jstl
                1.2
            
    
            
            
                org.projectlombok
                lombok
                1.18.20
                provided
            
    
            
            
            
                log4j
                log4j
                1.2.17
            
            
                org.slf4j
                slf4j-log4j12
                1.7.30
            
    
            
            
                junit
                junit
                4.13.1
                compile
            
    
            
            
                javax.servlet.jsp
                jsp-api
                2.2
                provided
            
    
            
            
                javax.servlet
                javax.servlet-api
                4.0.1
                provided
            
    
            
            
                org.thymeleaf
                thymeleaf-spring5
                3.0.12.RELEASE
            
    
            
            
                com.fasterxml.jackson.core
                jackson-databind
                2.13.0
            
    
        
    
  • 第二步:WEB-INF文件夹下,web.xml 配置拦截器拦截浏览器请求

    • 启动spring容器,加载spring全局配置文件
    • 配置SpringMVC前端控制器DispatcherServlet,对浏览器发送的请求进行统一处理,指定springMVC配置文件的地址
    • 字符编码过滤器
    • 配置HiddenHttpMethodFilter,过滤请求方式
    <?xml version="1.0" encoding="UTF-8"?>
    
        
        
        
          
          contextConfigLocation
          classpath:springApplicationConfig.xml
        
        
        
          org.springframework.web.context.ContextLoaderListener
        
    
      
      
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
        
          
          contextConfigLocation
          
          classpath:springMVC.xml
        
    
        
        1
      
    
      
        DispatcherServlet
        
        /  
      
    
      
      
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
          encoding
          UTF-8
        
        
        
          forceResponseEncoding
          true
        
        
          forceRequestEncoding
          true
        
      
      
        CharacterEncodingFilter
        /* 
      
    
      
      
      
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
      
      
        HiddenHttpMethodFilter
        /* 
      
    
      
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  • 第三步:resources资源目录下,springMVC.xml 配置SpringMVC

    • 开启扫描组件,扫描注解配置的类
    • 配置视图解析器
    • 开放对静态资源的访问
    • 开启mvc注解驱动
    <?xml version="1.0" encoding="UTF-8"?>
    
    
        
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
        
        
            
            
        
    
        
    
    
        
        
    
        
        
    
    
    
  • 第四步:resources文件夹下,配置数据库连接和日志文件,dbconfig.properties和log4j.properties

    dbconfig.properties

    mysql.driver=com.mysql.cj.jdbc.Driver
    mysql.url=jdbc:mysql://localhost:3306/mybatisdb?allowMultiQueries=true
    mysql.username=root
    mysql.password=wenhao
    

    log4j.properties

    log4j.rootLogger=DEBUG,A1
    
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
    
  • 第五步:resources文件夹下,springApplicationConfig.xml 全局配置文件,对Spring进行配置,与主要配置和业务逻辑有关

    • 开启扫描组件,这里无需扫描controller

    • 整合MyBatis

      1. 引入数据库配置文件 properties文件位置,classpath——>resources目录下
    1. 配置数据源(数据库连接池),可以使用c3p0或者Druid
    2. 配置Spring和MyBatis的整合:SqlSessionFactory,会指定MyBatis全局配置文件位置
    3. 配置sqlSession
    4. 配置扫描器,扫描自定义的mapper接口
    5. 配置一个可以进行批处理的sqlSession
    • 事务控制的配置(事务管理器)

      1. 建立与数据库连接池的映射
      2. 开启基于注解的事务
      3. 配置事务增强
    <?xml version="1.0" encoding="UTF-8"?>
    
    
        
    
        
        
            
        
    
        
        
        
    
        
        
            
            
            
            
            
            
        
    
        
        
            
            
            
            
            
            
        
    
        
        
            
            
        
    
        
        
            
            
        
    
        
        
            
            
        
    
        
        
            
            
            
            
        
    
        
        
            
                
                
                
                
            
        
    
    
    
  • 第六步:resources文件下,mybatisConfig.xml 配置MyBatis配置文件

    • 配置一些对MyBatis的属性设置(如:settings、typeAliases等,properties属性已经在外部进行配置了,即springApplicationConfig.xml文件中)
    <?xml version="1.0" encoding="UTF-8" ?>
    
    
    
        
            
            
            
            
        
        
        
            
            
                
                
            
        
    
    
    
  • 第七步:resources文件下,mbg.xml 配置逆向生成属性

    <?xml version="1.0" encoding="UTF-8"?>
    
    
        
        
        
    
            
            
                
            
    
            
            
            
    
            
            
                
            
    
            
            
                
                
            
    
            
            
            
                
            
    
            
            
            
                
            
    
            
            
            

1.4 测试

1.4.1 数据库的创建

创建一个名为ssm_crud的数据库

  • 这个数据库中有tbl_dept、tbl_emp两张表
CREATE TABLE `tbl_emp` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(255) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `tbl_dept` (
  `dept_id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  • 需要增加外键,即tbl_emp的d_id字段是tbl_dept的外键,从表tbl_dept的被引用字段dept_id是其主键

1.4.2 使用Spring单元测试对数据库进行操作

使用注解的方式导入Spring的配置文件,并且使用Spring单元测试(需添加依赖)

        
        
            org.springframework
            spring-test
            5.2.18.RELEASE
        

测试代码:

/*
*   推荐Spring项目使用Spring的单元测试,就可以自动注入我们需要的组件了
*       1. 导入SpringTest依赖,注意scope标签,要去掉test
*       2. @ContextConfiguration指定Spring配置文件的位置
*       3. autowired要使用的组件即可
* */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springApplicationConfig.xml"})
public class MapperTest {

    /*
    * ==========使用注解的方式===========
    *   由于先加载了Spring配置文件,所以使用注解,自动注入,获取实例
    * */
    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    SqlSession sqlSession;

    /*
    *   测试DepartmentMapper
    * */
    @Test
    public void testCRUD(){
//        // ===========传统方法============
//        // 1. 创建Spring IOC容器
//        ApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:springApplicationConfig.xml");
//        // 2. 从容器中获取mapper接口实例,因为在spring配置文件中,对mapper接口进行扫描并添加
//        DepartmentMapper departmentMapper = ioc.getBean(DepartmentMapper.class);

        // 1. 新增部门信息,使用插入信息参数是可以选择的,所以选择 可选择参数插入方法,即insertSelective,因为id是自增的
        departmentMapper.insertSelective(new Department(null, "开发部"));
        departmentMapper.insertSelective(new Department(null, "测试部"));

        // 2. 生成员工数据,测试员工的插入
        employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "jerry@123.com", 1));

        // 3. 批量插入多个员工:批量操作,需要在Spring全局配置文件中设置一个可以执行批量操作的sqlSession

//        for(){ // 如果直接使用自动注入的mapper对象,无论是循环多少次,都是建立了相应次数的sqlSession,并不是批量操作
//            employeeMapper.insertSelective(new Employee());
//        }
        // 使用在spring配置文件中已经配置好的批量处理sqlSession
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        for (int i = 0; i < 200; i++) {
            String uid = UUID.randomUUID().toString().substring(0, 5) + i;
            mapper.insertSelective(new Employee(null, uid, "W", uid + "@123.com", 1));
        }
        for (int i = 0; i < 200; i++) {
            String uid = UUID.randomUUID().toString().substring(0, 5) + i;
            mapper.insertSelective(new Employee(null, uid, "M", uid + "@qq.com", 2));
        }
        for (int i = 0; i < 200; i++) {
            String uid = UUID.randomUUID().toString().substring(0, 5) + i;
            mapper.insertSelective(new Employee(null, uid, "M", uid + "@gmail.com", 1));
        }

    }
}

1.5 完善项目结构

  • bean:又entity,实体层,实现对数据库表的映射,往往是一个数据对象。
  • controller:控制层,实现对浏览器发来的请求进行相应处理。
  • dao:数据访问对象层,创建接口,定义对数据库进行CRUD的操作方法,再建立与mapper xml配置文件的映射。
  • service:业务逻辑层,实现业务的真正逻辑,编写业务逻辑的代码,可以实现切面操作等