3. SSM 整合
3.1 需求
使用SpringMVC和MyBatis完成用户管理系统.
3.2 整合思路
spring+springmvc+mybaits的系统架构:
步骤:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
3.3 环境准备
表:
CREATE TABLE `tb_userinfo` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`name` VARCHAR(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户名称',
`gender` CHAR(2) COLLATE utf8mb4_bin NOT NULL DEFAULT '男' COMMENT '用户性别',
`age` INT(10) UNSIGNED DEFAULT NULL COMMENT '用户年龄',
`address` VARCHAR(20) COLLATE utf8mb4_bin NOT NULL COMMENT '用户籍贯',
`email` VARCHAR(50) COLLATE utf8mb4_bin NOT NULL COMMENT '用户邮箱',
`qq` VARCHAR(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户QQ',
`photo` VARCHAR(200) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户头像',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
依赖:
<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.version>5.2.15.RELEASE</spring.version>
</properties>
<dependencies>
<!--添加Spring-mvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--log4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.36</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
log4j.properties日志配置文件:
log4j.rootCategory=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
数据库配置文件: db.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.user=root
jdbc.password=123
#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
jdbc.acquireIncrement=5
#初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3
jdbc.initialPoolSize=5
#连接池中保留的最小连接数。
jdbc.minPoolSize=3
#连接池中保留的最大连接数。Default: 15
jdbc.maxPoolSize=10
3.4 整合Mybatis
编写Mapper接口
User.java
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String gender;
private Integer age;
private String address;
private String email;
private String qq;
private String photo;
}
UserMapper.java
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
public void insert(User user);
public void delete(int id);
public User selectById(int id);
public List<User> selectAll();
}
对应的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.suke.mapper.UserMapper">
<select id="selectById" resultType="User">
select * from tb_userinfo where id = #{id}
</select>
<select id="selectAll" resultType="User">
select * from tb_userinfo
</select>
<insert id="insert" parameterType="User">
<selectKey resultType="int" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
insert into tb_userinfo(name,gender,age,address,email,qq,photo)
values(#{name,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR},#{age,jdbcType=INTEGER},#{address,jdbcType=VARCHAR}
,#{email,jdbcType=VARCHAR},#{qq,jdbcType=VARCHAR},#{photo,jdbcType=VARCHAR})
</insert>
<delete id="delete">
delete from tb_userinfo where id = #{id}
</delete>
</mapper>
注意:我们所有的Sql映射文件都放在 src/main/resources/mapper目录下
添加一个applicationContext-mapper.xml配置文件:
配置:
数据源
SqlSessionFactory
mapper扫描器
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--加载properties
如果是多个properties文件, 文件路径与文件路径使用逗号分割 classpath:db.properties,classpath:log4j.properties
-->
<context:property-placeholder location="classpath:db.properties" file-encoding="UTF-8"/>
<!--配置一个C3p0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--数据库四大参数-->
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<!--连接池相关的参数-->
<!--初始连接数-->
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
<!--增量, 每次创建几个连接-->
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<!--最大连接数-->
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
<!--最小连接数 默认值等于初始连接数-->
<property name="minPoolSize" value="${jdbc.minPoolSize}"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.suke.pojo"/>
<!--加载sql映射文件 * 任意 一定要注意: classpath*: 如果不写, 后面*无效-->
<property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"/>
</bean>
<!--配置mapper扫描器 扫描指定包下所有的Mapper接口
创建Mapper接口代理对象, sqlSession.getMapper()并且保存到Spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描那个包下Mapper接口-->
<property name="basePackage" value="com.suke.mapper"/>
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
</bean>
</beans>
编写测试类:
UserMapperTest.java
import com.suke.pojo.User;
import lombok.extern.slf4j.Slf4j;
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;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-mapper.xml")
@Slf4j
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void selectById() {
User user = userMapper.selectById(1);
log.info("用户信息:{}",user);
}
}
测试结果:
3.5 整合Service
编写UserService接口以及实现类
UserService.java
public interface UserService {
public void addUser(User user);
public void deleteUser(Integer uid);
public User queryById(Integer uid);
public List<User> queryAll();
}
UserServiceImpl.java
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.insert(user);
}
@Override
public void deleteUser(Integer uid) {
if(uid == null){
throw new RuntimeException("id不能为空!");
}
userMapper.delete(uid);
}
@Override
public User queryById(Integer uid) {
if(uid == null){
throw new RuntimeException("id不能为空!");
}
return userMapper.selectById(uid);
}
@Override
public List<User> queryAll(){
return userMapper.selectAll();
}
}
添加一个applicationContext-service.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开始扫描注解-->
<context:component-scan base-package="com.suke.service"/>
<!--配置声明式事务管理-->
<!--配置一个事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!--配置事务策略: 对业务层的方法进行怎么样事务管理-->
<tx:attributes>
<tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="add*" rollback-for="java.lang.Exception"/>
<tx:method name="update*" rollback-for="java.lang.Exception"/>
<tx:method name="del*" rollback-for="java.lang.Exception"/>
<tx:method name="*" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!--把事务通知类txAdvice与业务层的类方法进行织入: AOP的技术-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="mypointcut" expression="execution(* com.suke.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/>
</aop:config>
</beans>
3.6 整合SpringMVC
SpringMVC是Spring框架的一个子模块,所以我们不需要进行任何整合,只需要把SpringMVC引入到项目即可
编写UserController.java
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("queryAll")
public ModelAndView queryAll(){
ModelAndView modelAndView = new ModelAndView();
List<User> users = userService.queryAll();
modelAndView.addObject("users",users);
modelAndView.setViewName("list");
return modelAndView;
}
}
springmvc.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: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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- SpringMVC的配置 -->
<!-- 扫描Controller的注解 -->
<context:component-scan base-package="com.suke.controller"></context:component-scan>
<!-- 配置注解的处理器映射器和注解的处理器适配器 -->
<mvc:annotation-driven/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp视图的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp视图的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.7 Spring与Web的整合
加载spring容器,配置springmvc前置控制器。在web.xml文件中进行配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 加载Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!-- 配置Spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置post乱码处理 -->
<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>
<!-- 配置SpringMVC的前端控制器 -->
<servlet>
<servlet-name>springmvc</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>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>