0%

SSM框架整合

SSM(Spring、SpringMVC、MyBatis)

整合步骤

  1. Mybatis配置文件的编写和相关实体类的引入
  2. 编写Spring MVC配置文件
    1. 配置扫描控制器
    2. 定义视图解析器
    3. 两个标准配置
  3. 编写Spring配置文件
    1. 配置组件扫描,过滤控制器
    2. 配置数据源
    3. 整合Mybatis
      1. 目的:(1)Spring管理所有组件,mapper的实现类;(2)Spring来管理事务
      2. 结果:mybatis-config.xml的大部分功能被替代了
    4. 引入事务管理器

Maven

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!-- spring-aop是基于aspect, 因此导入aspectjweaver -->
<dependency>
<groupId>org.apache.geronimo.bundles</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8_2</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- mybatis-spring, mybatis整合spring的jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!-- MBG -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?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_4_0.xsd"
version="4.0">

<!-- 1.启动Spring容器 -->
<context-param>
<!-- 配置Spring配置文件的位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 2.SpringMVC的前端控制器, 拦截所有请求 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 配置SpringMVC配置文件的位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.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>

<!-- 3.字符编码过滤器, 一定放在所有过滤器的前面 -->
<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>
<!-- 是否需要字符编码过滤器设置请求编码, 设置的字符集为encoding -->
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- 是否需要字符编码过滤器设置响应编码, 设置的字符集为encoding -->
<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>

<!-- 4.REST风格的URI -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

spring-mvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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:mvc="http://www.springframework.org/schema/mvc"
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/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">

<!-- SpringMVC配置文件, 包含网站跳转逻辑的控制配置 -->
<context:component-scan base-package="xyz.jyke.controller" use-default-filters="false">
<!-- 只扫描控制器 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 配置视图解析器, 方便页面返回 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>

<!-- 两个标准配置 -->
<!-- 将SpringMVC不能处理的请求交给Tomcat -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- 能支持SpringMVC更高级的一些功能, JSR303校验, 快捷的ajax...映射动态请求 -->
<mvc:annotation-driven></mvc:annotation-driven>

</beans>

dbconfig.properties

1
2
3
4
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm
jdbc.username=root
jdbc.password=12345678

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- Spring配置文件, 这里主要配置和业务逻辑有关的 -->
<context:component-scan base-package="xyz.jyke">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 引入外部properties文件 -->
<context:property-placeholder location="classpath:dbconfig.properties"></context:property-placeholder>
<!-- 数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!-- 配置MyBatis整合 -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定MyBatis全局配置文件的位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 指定数据源 -->
<property name="dataSource" ref="dataSource"/>
<!--&lt;!&ndash; 指定MyBatis Mapper文件的位置 &ndash;&gt;-->
<property name="mapperLocations" value="classpath:xyz/jyke/mapper/*.xml" />
</bean>

<!-- 配置扫描器, 将Mapper接口生成代理注入到Spring -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定mapper接口所在包 -->
<property name="basePackage" value="xyz.jyke.mapper"/>
<!-- 指定sqlSessionFactoryBean配置在Spring中的id值 -->
<property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
</bean>
<!-- 配置一个专门用来进行Batch操作的sqlSession -->
<bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 指定sqlSessionFactory -->
<constructor-arg name="sqlSessionFactory" ref="sessionFactory"/>
<!-- 设置执行类型为Batch -->
<constructor-arg name="executorType" value="BATCH"/>
</bean>

<!-- 事务控制 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 控制主数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 使用xml配置形式的事务(重要的都是使用xml) -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut id="txPoint" expression="execution(* xyz.jyke.service.*.*(..))"/>
<!-- 配置事务增强 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"></aop:advisor>
</aop:config>
<!-- 配置事务增强, 事务如何切入; 并指定事务管理器, 事务管理器名称默认就是transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 所有方法都是事务方法 -->
<tx:method name="*"/>
<!-- 以get开始的方法设置只读事务, 底层有优化 -->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>

</beans>

log4j.properties

1
2
3
4
5
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

mybatis-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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>
<settings>
<!-- 开启驼峰命名法 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 日志 -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 批量起别名 -->
<typeAliases>
<package name="xyz.jyke.pojo"/>
</typeAliases>
</configuration>

项目结构

!image-20211006151404493

测试 SSM

测试查询全部

SQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
CREATE TABLE `tbl_dept` (
`dept_id` INT(10) NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO tbl_dept(`dept_id`, `dept_name`) VALUES (1, '开发部');
INSERT INTO tbl_dept(`dept_id`, `dept_name`) VALUES (2, '测试部');

CREATE TABLE `tbl_employee` (
`emp_id` INT(10) NOT NULL AUTO_INCREMENT,
`emp_name` VARCHAR(30) DEFAULT NULL,
`emp_gender` VARCHAR(30) DEFAULT NULL,
`emp_email` VARCHAR(30) DEFAULT NULL,
`d_id` INT(10) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (1, 'Hong', '男', '[email protected]', 1);
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (2, 'Tom', '男', '[email protected]', 2);
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (3, 'Jerry', '男', '[email protected]', 1);
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (4, 'Bob', '男', '[email protected]', 1);
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (5, 'Lucy', '女', '[email protected]', 2);
INSERT INTO `tbl_employee`(`emp_id`, `emp_name`, `emp_gender`, `emp_email`, `d_id`) VALUES (6, 'Jessica', '女', '[email protected]', 2);

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
package xyz.jyke.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
private Integer id;
private String name;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package xyz.jyke.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String name;
private String gender;
private String email;
private Dept dept;
}

Mapper 接口

1
2
3
4
package xyz.jyke.mapper;

public interface DeptMapper {
}
1
2
3
4
5
6
7
8
9
package xyz.jyke.mapper;

import xyz.jyke.pojo.Employee;

import java.util.List;

public interface EmployeeMapper {
List<Employee> getAll();
}

Mapper.xml 文件

1
2
3
4
5
6
7
8
<?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="xyz.jyke.mapper.DeptMapper">
<resultMap id="BaseResultMapDept" type="xyz.jyke.pojo.Dept">
<id column="dept_id" jdbcType="INTEGER" property="id" />
<result column="dept_name" jdbcType="VARCHAR" property="name" />
</resultMap>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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="xyz.jyke.mapper.EmployeeMapper">
<resultMap id="BaseResultMapEmp" type="xyz.jyke.pojo.Employee">
<id column="emp_id" jdbcType="INTEGER" property="id" />
<result column="emp_name" jdbcType="VARCHAR" property="name" />
<result column="emp_gender" jdbcType="CHAR" property="gender" />
<result column="emp_email" jdbcType="VARCHAR" property="email" />
</resultMap>
<resultMap id="EmployeeJoin" type="Employee" extends="BaseResultMapEmp">
<association property="dept" resultMap="xyz.jyke.mapper.DeptMapper.BaseResultMapDept"></association>
</resultMap>


<select id="getAll" resultMap="EmployeeJoin">
select * from ssm.tbl_employee left join ssm.tbl_dept on d_id = dept_id
</select>
</mapper>

service 接口

1
2
3
4
5
6
7
8
9
package xyz.jyke.service;

import xyz.jyke.pojo.Employee;

import java.util.List;

public interface EmployeeService {
List<Employee> getAll();
}

serviceimpl 实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package xyz.jyke.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.jyke.mapper.EmployeeMapper;
import xyz.jyke.pojo.Employee;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;

@Override
public List<Employee> getAll() {
// 使用 MyBatis-Spring 之后,你不再需要直接使用 SqlSessionFactory 了,
// 因为你的 bean 可以被注入一个线程安全的 SqlSession,
// 它能基于 Spring 的事务配置来自动提交、回滚、关闭 session。
return employeeMapper.getAll();
}
}

EmployeeController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package xyz.jyke.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import xyz.jyke.pojo.Employee;
import xyz.jyke.service.EmployeeService;

import java.util.List;

@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;

@RequestMapping("/")
public String index() {
System.out.println("===============index controller=============");
//设置视图名称,决定了我们要跳转到的页面,这个会被thymeleaf解析(加前缀和后缀)
return "index";
}

@GetMapping("/employee")
public String getAll(Model model){
List<Employee> employees = employeeService.getAll();
model.addAttribute("employees", employees);
return "list";
}

}

整合完毕!!!

list.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<%--
Created by IntelliJ IDEA.
User: 谢禹宏
Date: 2021-04-22
Time: 10:37
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
<table align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Email</th>
<th>DeptName</th>
</tr>
<c:forEach items="${requestScope.employees}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.gender}</td>
<td>${employee.email}</td>
<td>${employee.dept.name}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

访问 /employee

控制台打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
## MyBatis-Spring帮我们创建了sqlSession对象
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Creating a new SqlSession
## 并且注册了一个transaction事务到sqlSession对象中
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Registering transaction synchronization for SqlSession [[email protected]]
## JDBC Connection交给Spring管理
[http-nio-8080-exec-6] [org.mybatis.spring.transaction.SpringManagedTransaction]-[DEBUG] JDBC Connection [[email protected]] will be managed by Spring
## MyBatis发送sql
[http-nio-8080-exec-6] [org.hong.mapper.EmployeeMapper.getAll]-[DEBUG] ==> Preparing: select emp_id, emp_name, emp_gender, emp_email, dept_id, dept_name from tbl_employee left join tbl_dept on d_id = dept_id
[http-nio-8080-exec-6] [org.hong.mapper.EmployeeMapper.getAll]-[DEBUG] ==> Parameters:
[http-nio-8080-exec-6] [org.hong.mapper.EmployeeMapper.getAll]-[DEBUG] <== Total: 2
## 进入事务和sqlSession释放环节
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Releasing transactional SqlSession [[email protected]]
## 提交事务
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Transaction synchronization committing SqlSession [[email protected]]
## 注销事务
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Transaction synchronization deregistering SqlSession [[email protected]]
## 关闭sqlSession
[http-nio-8080-exec-6] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Transaction synchronization closing SqlSession [[email protected]]