文章目录
前言
本篇记录一下SSM的整合
一、SSM
即Spring、SpringMVC、Mybatis三个框架。
二、整合步骤
1.关系梳理
在整合之前,先梳理一下SSM三个部分之间的关系。
Mybatis:
持久层框架,代替JDBC,需要配置mybatis-config.xml文件和dbproperties,原来的dao和daoImpl文件被mapper接口和mapper.xml映射文件所替代。使用时需要创建 SqlSession,通过 SqlSession获得接口的代理对象。通过接口的代理对象调用mapper接口实现的方法。
spring:
开源的应用程序框架,其特点是IOC(控制反转)和AOP(面向切面编程)。IOC实现了bean对象的自动创建和管理,当我们需要某个对象时,无需手动创建。只需要调用在spring容器中注册的名字即可,spring会自动帮我们创建对象。使用spring时,需要配置applicationContext.xml文件。导入相关依赖。
springMVC:
其本身是spring的一部分,主要提供的是一套前端解决方案和MVC解耦合分层开发模式,构建在servlet基础上,使jsp请求服务端数据变得更加容易,各部分之间耦合度降低。利于代码的维护,在使用时,主要使用注解开发,主要表现为将原有的servlet用controller代替。
它们之间整合的关系为,mybatis代替持久层,spring提供自动创建对象,springMVC提供了MVC开发模式,并使用注解和controller代替servlet。
2.整合
了解了各部分该干的分别是什么就可以着手进行整合了。
- 创建项目
- 补全项目结构
- 导入依赖
- 配置mybatis-config.xml
- 配置数据源db.properties
- 配置spring配置文件applicationContext.xml
- 配置springMVC.xml
- 配置web.xml文件
- 搭建前端页面
- 配置后端控制器
- 实现业务层
- 实现持久层
- 测试运行
整合开始
前两个步骤略
导入依赖:
<?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.lzl</groupId>
<artifactId>SSM_Integrate</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSM_Integrate Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- 单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring的核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!-- spring的切面 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!-- 对数据访问层的支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- spring整合mybatis单独的jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--德鲁伊-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- springmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- lombok注解依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--配置jackson 否则返回自定义结果处理对象会报错-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
</dependencies>
<build>
<!-- 资源编译至target目录配置 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>*.xml</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 根标签 -->
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
</configuration>
由于我们可以使用spring的IOC来对bean进行统一的管理,这里就不需要再配置过多的东西,我们只需要把日志配置放在这里即可
配置数据源db.properties
#驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false
#用户名
jdbc.username=...
#密码
jdbc.password=....
#初始化连接数,最大,最小连接数
jdbc.initialSize=5
jdbc.minIdle=3
jdbc.maxActive=20
#等待超时的时间
jdbc.maxWait=0
#间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
jdbc.timeBetweenEvictionRunsMillis=600000
#一个连接在池中最小生存的时间,单位是毫秒
jdbc.minEvictableIdleTimeMillis=300000
这里我们使用了一个德鲁伊数据库连接池技术,增加我们的项目资源利用率。降低开销。
配置applicationContext.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: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注解扫描 扫描了所有的注解 -->
<context:component-scan base-package="com.lzl"/>
<!-- 加载db.properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!--掌握 基于 AspectJ 的 注解 的 AOP实现 配置-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 加载数据源 -->
<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}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${jdbc.maxWait}"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
</bean>
<!-- 3创建SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 加载数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 设置别名 -->
<property name="typeAliasesPackage" value="com.lzl.entity"/>
</bean>
<!-- 创建mapper扫描器 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lzl.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
spring配置文件是整合文件的核心,绝大多数的mybatis配置都可以在这里进行配置。
配置springMVC.xml
<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">
<!-- 告知springmvc 哪些包中 存在 被注解的类 springmvc取代的是servlet,所以只扫描controller -->
<context:component-scan base-package="com.lzl.controller"></context:component-scan>
<!-- 注册注解开发驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器
作用:1.捕获后端控制器的返回值="index"
2.解析: 在返回值的前后 拼接 ==> "/index.jsp"
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/> <!-- /** 任意多级任意路径 -->
<!-- <mvc:exclude-mapping path="/login"/> <!–不拦截此路径–>-->
<bean class="com.lzl.interceptor.MyInterceptor"></bean> <!--拦截器类-->
</mvc:interceptor>
</mvc:interceptors>
<!--处理静态资源的访问-->
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:resources mapping="/managePage/**" location="/managePage/"/>
</beans>
需要注意的是,SpringMVC配置的大多是和前端处理有关的内容,不涉及后端的配置。
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_4_0.xsd"
version="4.0">
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- spring 配置文件 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 封装了一个监听器,帮助加载 Spring 的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置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>-->
<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>
<!--德鲁伊数据连接池技术 监控中心-->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<!--过滤器,设置编码格式-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
web.xml文件配置的一般是对SSM整合的补充,是全局的配置。
搭建前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>电影管理</title>
<link rel="stylesheet" type="text/css" href="../lib/layui-v2.6.3/css/layui.css"/>
<style>
body{
background-color:#eeeeee;
}
.layui-table-tool{
padding-top: 10px;
padding-bottom: 0px;
}
.layui-table, .layui-table-view {
margin: 0px 0;
}
#transferDiv{
display: none;
width: 500px;
margin: 0px auto;
}
</style>
</head>
<body>
<div class="layui-card" style="margin-left: 10px; margin-top: 3px; padding-top: 10px; margin-right: 10px; margin-bottom: 0px; ">
<!-- 头部-->
<div class="layui-card-header">
<!-- 顶部工具栏 -->
<div class="layui-form-item" id="topBar">
<form class="layui-form" onsubmit="return false;">
<label class="layui-form-label">姓名:</label>
<input type="text" id="emp_name" name="emp_name" style="width:150px;" class="layui-input layui-input-inline"/>
<label class="layui-form-label">部门:</label>
<div class="layui-input-inline" style="width:100px;">
<select id="dept_no" class="option">
<option value=""></option>
</select>
</div>
<label class="layui-form-label">状态:</label>
<div class="layui-input-inline" style="width:100px;">
<select id="emp_status" >
<option value="">--全部--</option>
<option value="0">在职</option>
<option value="1">离职</option>
</select>
</div>
<label class="layui-form-label">入职时间:</label>
<input type="text" id="begin" name="begin" style="width:100px;" class="layui-input layui-input-inline"/>
<label class="layui-form-label" style="width: 20px; text-align: center">至</label>
<input type="text" id="end" name="end" style="width:100px;" class="layui-input layui-input-inline"/>
<!--操作按钮 -->
<label class="layui-form-label" style="width: 20px;"></label>
<button class="layui-btn layui-btn-sm " id="search"><i class="layui-icon"></i></button>
</form>
</div>
</div>
<!-- 中部-->
<div class="layui-card-body" style="margin-top: 0px;padding-top: 0px; height: 528px">
<!-- 表格工具栏 -->
<script type="text/html" id="topTool">
<button type="button" class="layui-btn layui-btn-xs" lay-event="add" >
<i class="layui-icon" ></i>添加
</button>
<button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delAll">
<i class="layui-icon"></i>批量删除
</button>
<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="put">
<i class="layui-icon"></i>入职办理
</button>
</script>
<!-- 行内工具栏 -->
<script type="text/html" id="barDemo">
<button class="layui-btn layui-btn-xs layui-bg-orange" lay-event="edit" id="upbtn"><i class="layui-icon"></i></button>
<button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete" id="dlbtn"><i class="layui-icon"></i></button>
</script>
<!-- 数据表格 -->
<table class="layui-table" style="margin-top: 0px;" id="tableDemo" lay-filter="table"></table>
</div>
<!-- 修改弹层区域 -->
<div class="layui-form-item" id="upye" style="display:none;">
<form class="layui-form" onsubmit="return false;" lay-filter="up" id="up">
<div class="layui-form-item">
<label class="layui-form-label">姓名:</label>
<div class="layui-input-block">
<input type="hidden" name="emp_no" value=""/>
<input type="text" name="emp_name" class="layui-input"style="width:200px;"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别:</label>
<div class="layui-input-block" style="width:200px;">
男:<input type="radio" value="男" name="emp_gender" />
女:<input type="radio" value="女" name="emp_gender" />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" lay-verify="required" name="emp_age" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">部门:</label>
<div class="layui-input-block" style="width:200px;">
<select name="emp_dept_no" class="option" lay-verify="required" lay-search="">
<option value=""></option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">职位:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_position" lay-verify="required" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">薪资:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_salary"lay-verify="required" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">状态:</label>
<div class="layui-input-block" style="width:200px;">
<select name="emp_status" lay-verify="required">
<option value="">--全部--</option>
<option value="0">在职</option>
<option value="1">离职</option>
</select>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" style="width:200px;">
<button class="layui-btn layui-btn-sm layui-bg-red" lay-submit="" lay-filter="update">提交</button>
</div>
</div>
</form>
</div>
<!-- 修改结束-->
<!--新增弹层区域-->
<div class="layui-form-item" id="addPage" style="display:none;">
<form class="layui-form" onsubmit="return false;" lay-filter="add" id="addNew">
<div class="layui-form-item">
<label class="layui-form-label">姓名:</label>
<div class="layui-input-block">
<input type="hidden" name="emp_no" value=""/>
<input type="text" name="emp_name" lay-verify="required" class="layui-input"style="width:200px;"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别:</label>
<div class="layui-input-block" style="width:200px;">
男:<input type="radio" value="男" name="emp_gender" checked/>
女:<input type="radio" value="女" name="emp_gender" />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_age" lay-verify="required" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">部门:</label>
<div class="layui-input-block" style="width:200px;">
<select name="emp_dept_no" lay-verify="required" class="option">
<option value=""></option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">入职时间:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_hire_time" id="year2" class="layui-input Time"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">职位:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_position" lay-verify="required" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">薪资:</label>
<div class="layui-input-block" style="width:200px;">
<input type="text" name="emp_salary" lay-verify="required" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" style="width:200px;">
<button class="layui-btn layui-btn-sm layui-bg-red" lay-submit="" lay-filter="addBtn">提交</button>
</div>
</div>
</form>
</div>
<!-- 新增结束-->
</div>
<!--自定义模板-->
<script type="text/html" id="status">
{{# if(d.emp_status == 0){ }}
<span>在职</span>
{{# } else { }}
<span>离职</span>
{{# } }}
</script>
<!--穿梭框 -->
<div id="transferDiv" style="margin-top: 5px">
<div id="transferDemo" style="margin-left: 10px;"></div>
</div>
<script type="text/javascript" src="../lib/layui-v2.6.3/layui.js" ></script>
<script src="/static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
layui.use(['table','layer','form','laydate','transfer'],function(){
var table = layui.table;
var layer = layui.layer;
var form = layui.form;
var laydate = layui.laydate;
var transfer = layui.transfer;
var $ = layui.$;
//渲染时间
laydate.render({
elem:'#begin',
});
laydate.render({
elem:'#end',
});
laydate.render({
elem:'#year2',
});
//渲染下拉框
$.post("/department/getDepartment",{},function(res){
//遍历集合
$.each(res.data,function(index,item){
//<option value="item.cid">item.cName</option>
$(".option").append(new Option(item.dept_name,item.dept_no));
});
//渲染layui下拉单
layui.form.render();
},"json");
//表格渲染
table.render({
elem: '#tableDemo',//指定原始表格元素选择器(推荐id选择器)
even: true,
page: true,
method:'post',
width: 1250,
toolbar: '#topTool',
url:'/employee/getAll',
cols:[[
{type: 'checkbox', fixed: 'left'},
{fixed:'left',type:'numbers', title:'编号'},
{field:'emp_name', title:'姓名',width:100,align:'center'},
{field:'emp_gender', title:'性别',width:80,align:'center'},
{field:'emp_age', title:'年龄',width:80,align:'center'},
{templet : '<span>{{d.department.dept_name}}</span>', title:'部门',align:'center'},
{field:'emp_salary', title:'薪资',align:'center'},
{field:'emp_hire_time', title:'入职时间',align:'center'},
{field:'emp_position', title:'职位',align:'center'},
{templet : '#status',title:'状态',align:'center'},
{fixed: 'right', title:'操作', width:100, align:'center', toolbar: '#barDemo'}
]],
id:"retable",
});
//重载函数
active = {
reload : function(){
table.reload('retable',{
where:{
"emp_name" : $("#emp_name").val(), //名字
"dept_no" : $("#dept_no").val(), //部门
"emp_status" : $("#emp_status").val(), //状态
"begin" : $("#begin").val(), //开始年份
"end" : $("#end").val(), //结束年份
}
,page: {
curr: $(".layui-laypage-em").next().html() //重新从第当前页开始
}
});
}
}
//多条件查询
$("#search").click(function(){
active.reload();
});
// 头工具栏事件
table.on('toolbar(table)', function(obj){
var checkStatus = table.checkStatus(obj.config.id)
,data = checkStatus.data; //获取选中的数据
switch(obj.event){
case 'add':
layer.open({
type : 1,
title : '添加数据',
area : [ '450px', '550px' ],
content : $('#addPage')
//这里content是一个DOM,注意:最好该元素要存放在body最外层,否则可能被其它的相对元素所影响
});
break;
case 'delAll':
if(data.length === 0){
layer.msg('请至少选择一行');
} else if(data.length > 1){
$list = checkStatus.data;
$ids = [];
for (var i = 0; i < $list.length; i++) {
$ids[i] = $list[i].emp_no;
}
$strIds = ""
for (var i = 0; i < $ids.length; i++) {
$strIds += $ids[i]+",";
}
layer.confirm("确认删除所有选中行吗?", function(index){
var delUrl ="/employee/deleteInfo";
var strData = {
"emp_no": $strIds
}
$.post(delUrl, strData, function(res){
$r = res;
if ($r.code != 0) {
active.reload();
layer.msg($r.msg, {
icon: 6,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
} else {
layer.msg($r.msg, {
icon: 5,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
}
}, "json");
});
}
break;
case 'put':
layer.open({
type : 1,
title : '员工状态',
area : [ '500px', '468px' ],
content : $('#transferDiv')
//这里content是一个DOM,注意:最好该元素要存放在body最外层,否则可能被其它的相对元素所影响
});
//请求穿梭框的数据
$.get("/employee/getAllData",{},function (resData1){//请求所有的数据
$data_lift = resData1.data;
var alreadyPut = [];//准备接收在职数据
//请求在职数据
$.get("/employee/getAllPutData",{},function (resData2){
$data_right = resData2.data;
if($data_right.length > 0) { //如果有在职
for(var i = 0; i < $data_right.length; i++) { //遍历
alreadyPut.push($data_right[i].emp_no); //将在职人员工号添加到数组
}
}
//穿梭框渲染
transfer.render({
elem: '#transferDemo', //绑定元素
title: ['离职', '在职'],//标题
showSearch: true,//开启搜索
data: $data_lift,//左侧数据
value: alreadyPut,//右侧数据
parseData: function(r) {//数据处理
return {
"value": r.emp_no,
"title": r.emp_name,
}
},
id: 'transfer_1', //定义索引
//穿梭事件
onchange: function(obj, index) {
//obj 被穿梭的数据
//index 0 说明数据来自于左边 反之来自于右边
if (index == "0") {
//入职
$emp_nos1 = "";
for (var i = 0; i < obj.length; i++) {
$emp_nos1 += obj[i].value+",";
}
$.post("/employee/putOnData", {"emp_no":$emp_nos1}, function (res) {
if (res.code != 0) {
layer.closeAll();
layer.alert(res.msg, {icon: 6});
active.reload();
}else {
layer.alert(res.msg);
}
}, "json");
} else {
//离职
$emp_nos2 = "";
for (var i = 0; i < obj.length; i++) {
$emp_nos2 += obj[i].value+",";
}
$.post("/employee/putDownData", {"emp_no":$emp_nos2}, function (res) {
if (res.code != 0) {
layer.closeAll();
layer.alert(res.msg, {icon: 6});
active.reload();
}else {
layer.alert(res.msg);
}
}, "json");
}
}
});
},'json');
},'json')
break;
};
});
//行内监听
table.on('tool(table)', function(obj){ //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
var data = obj.data; //获得当前行数据
if( obj.event =="edit"){
form.val('up',data);
layer.open({
type: 1,
title:"你正在进行修改操作",
area: ['450px', '500px'],
content: $('#upye') //这里content是一个DOM,注意:最好该元素要存放在body最外层,否则可能被其它的相对元素所影响
});
}else if(obj.event =="delete"){
layer.confirm("确认删除["+ data.emp_name +"]吗?", function(index){
var delUrl ="/employee/deleteInfo";
var strData = {
"emp_no": data.emp_no
}
$.post(delUrl, strData, function(res){
$r = res;
if ($r.code != 0) {
active.reload();
layer.msg($r.msg, {
icon: 6,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
} else {
layer.msg($r.msg, {
icon: 5,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
}
}, "json");
});
};
});
//添加实现
form.on("submit(addBtn)", function() {
//添加请求
$.post("/employee/addNew", $("#addNew").serialize(), function(res) {
$r = res;
if ($r.code != 0) {
active.reload();
layer.closeAll();
$("#addNew")[0].reset();
layer.msg($r.msg, {
icon: 6,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
}else{
layer.msg($r.msg, {icon : 5});
}
}, "json");
});
//修改实现
form.on('submit(update)', function(data){
//alert($("#up").serialize());
$.post('/employee/updateInfo',$("#up").serialize(),function(res){
$r = res;
//取出表单值用form表单的id
if($r.code != 0){
active.reload();
layer.closeAll();
layer.msg($r.msg, {
icon: 6,
time: 1000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
});
}else{
layer.msg($r.msg, {icon : 5});
}
},'json')
});
});
</script>
</body>
</html>
控制器的实现
package com.lzl.controller;
import com.lzl.entity.Employee;
import com.lzl.service.EmployeeService;
import com.lzl.util.EmployeeInfoUtil;
import com.lzl.util.ResultLayUi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
/**
* --效率,是成功的核心关键--
* --自负,会让每个人都屈膝下跪--
*
* @Author lzl
* @Date 2022/10/2 20:05
*/
@Controller
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService service;
@RequestMapping(value = "getAll",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> getAllByKey(EmployeeInfoUtil infoUtil){
return service.getAllEmployee(infoUtil);
}
@RequestMapping(value = "updateInfo",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> updateInfo(Employee employee){
return service.updateEmployeeInfo(employee);
}
@RequestMapping(value = "addNew",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> addNew(Employee employee){
return service.addNewEmployee(employee);
}
@RequestMapping(value = "deleteInfo",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> deleteInfo(String emp_no){
return service.deleteEmployeeInfo(emp_no);
}
@RequestMapping(value = "getAllData",method = RequestMethod.GET)
@ResponseBody
public ResultLayUi<Employee> getAllData(){
return service.getAllData();
}
@RequestMapping(value = "getAllPutData",method = RequestMethod.GET)
@ResponseBody
public ResultLayUi<Employee> getAllPutData(){
return service.getPutData_s();
}
@RequestMapping(value = "putOnData",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> putOnData(String emp_no){
return service.putOnEmployee_s(emp_no);
}
@RequestMapping(value = "putDownData",method = RequestMethod.POST)
@ResponseBody
public ResultLayUi<Employee> putDownData(String emp_no){
return service.putDownEmployee_s(emp_no);
}
}
实现业务层
package com.lzl.service;
import com.lzl.entity.Employee;
import com.lzl.util.EmployeeInfoUtil;
import com.lzl.util.ResultLayUi;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface EmployeeService {
/**
* 获得所有的员工
* @return 符合前端解析的json数据 code,msg,count,data
*/
ResultLayUi<Employee> getAllEmployee(EmployeeInfoUtil infoUtil);
/**
* 新增员工
* @param employee
* @return 受影响行数
*/
ResultLayUi<Employee> addNewEmployee(Employee employee);
/**
* 修改数据
* @param employee 实体
* @return 受影响行数
*/
ResultLayUi<Employee> updateEmployeeInfo(Employee employee);
/**
* 删除数据
* @param
* @return
*/
ResultLayUi<Employee> deleteEmployeeInfo(String emp_nos);
/**
* 获得所有员工信息
* @return list集合
*/
ResultLayUi<Employee> getAllData();
/**
* 获得所有在职员工信息
* @return list集合
*/
ResultLayUi<Employee> getPutData_s();
/**
*入职
* @param params
* @return 入职成功 1 或者失败 0
*/
ResultLayUi<Employee> putOnEmployee_s(String params);
/**
*离职
* @param params
* @return 离职成功 1 或者失败 0
*/
ResultLayUi<Employee> putDownEmployee_s(String params);
}
接口实现
package com.lzl.service.impl;
import com.lzl.entity.Employee;
import com.lzl.mapper.EmployeeMapper;
import com.lzl.service.EmployeeService;
import com.lzl.util.EmployeeInfoUtil;
import com.lzl.util.ResultLayUi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper mapper;
/**
* 获得所有的员工
*
* @return 符合前端解析的json数据 code,msg,count,data
*/
@Override
public ResultLayUi<Employee> getAllEmployee(EmployeeInfoUtil infoUtil) {
List<Employee> list = mapper.getAll(infoUtil);
int count = mapper.getCount(infoUtil);
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
if (list.size() > 0){
resultLayUi.setCount(count);
resultLayUi.setData(list);
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("没有数据");
}
return resultLayUi;
}
/**
* 新增员工
*
* @param employee
* @return 受影响行数
*/
@Override
public ResultLayUi<Employee> addNewEmployee(Employee employee) {
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
Integer key = mapper.addNew(employee);
if (key!=0){
resultLayUi.setCode(1);
resultLayUi.setMsg("新增成功");
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("新增失败");
}
return resultLayUi;
}
/**
* 修改数据
*
* @param employee
* @return 受影响行数
*/
@Override
public ResultLayUi<Employee> updateEmployeeInfo(Employee employee) {
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
Integer key = mapper.updateInfo(employee);
if (key!=0){
resultLayUi.setCode(1);
resultLayUi.setMsg("更新成功");
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("更新失败");
}
return resultLayUi;
}
/**
* 删除数据
*
* @param
* @return
*/
@Override
public ResultLayUi<Employee> deleteEmployeeInfo(String emp_nos) {
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
String[] strList = emp_nos.split(",");
//设置一个数组
ArrayList<String> params = new ArrayList<>();
for (String s : strList) {
params.add(s);
}
Integer key = mapper.deleteInfoByEmp_no(params);
if (key!=0){
resultLayUi.setCode(1);
resultLayUi.setMsg("删除成功");
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("删除失败");
}
return resultLayUi;
}
/**
* 获得系统所有员工
*
* @return list集合
*/
@Override
public ResultLayUi<Employee> getAllData() {
List<Employee> list = mapper.getAllData_m();
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
if(list.size()!=0){
resultLayUi.setCode(1);
resultLayUi.setData(list);
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("没有数据");
}
return resultLayUi;
}
/**
* 获得所有在职员工
*
* @return list集合
*/
@Override
public ResultLayUi<Employee> getPutData_s() {
List<Employee> list = mapper.getPutData_m();
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
if(list.size()!=0){
resultLayUi.setCode(1);
resultLayUi.setData(list);
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("没有数据");
}
return resultLayUi;
}
/**
* 入职
*
* @param
* @return 入职成功或者失败
*/
@Override
public ResultLayUi<Employee> putOnEmployee_s(String emp_nos) {
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
String[] strList = emp_nos.split(",");
//设置一个数组
ArrayList<String> params = new ArrayList<>();
for (String s : strList) {
params.add(s);
}
Integer key = mapper.putOnEmployee_m(params);
if (key!=0){
resultLayUi.setCode(1);
resultLayUi.setMsg("入职办理成功");
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("入职办理失败");
}
return resultLayUi;
}
/**
* 离职
*
* @param
* @return 离职成功 1 或者失败 0
*/
@Override
public ResultLayUi<Employee> putDownEmployee_s(String emp_nos) {
ResultLayUi<Employee> resultLayUi = new ResultLayUi<>();
String[] strList = emp_nos.split(",");
//设置一个数组
ArrayList<String> params = new ArrayList<>();
for (String s : strList) {
params.add(s);
}
Integer key = mapper.putDownEmployee_m(params);
if (key!=0){
resultLayUi.setCode(1);
resultLayUi.setMsg("离职办理成功");
}else {
resultLayUi.setCode(0);
resultLayUi.setMsg("离职办理失败");
}
return resultLayUi;
}
}
实现持久层
package com.lzl.mapper;
import com.lzl.entity.Employee;
import com.lzl.util.EmployeeInfoUtil;
import org.apache.ibatis.annotations.Param;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* --效率,是成功的核心关键--
* --自负,会让每个人都屈膝下跪--
*
* @Author lzl
* @Date 2022/9/20 10:25
*/
public interface EmployeeMapper {
/**
* 获得所有的员工
* @return 前端所需要解析的json,code,msg,count,data
*/
List<Employee> getAll(EmployeeInfoUtil infoUtil);
/**
* 获得数据总数
* @return int count
*/
Integer getCount(EmployeeInfoUtil infoUtil);
/**
* 新增员工数据
* @param employee
* @return 受影响行数
*/
Integer addNew(Employee employee);
/**
* 修改数据
* @param employee
* @return 受影响行数
*/
Integer updateInfo(Employee employee);
/**
* 删除数据
* @param params
* @return 受影响行数
*/
Integer deleteInfoByEmp_no(@Param("emp_nos")ArrayList<String> params);
/**
* 获得数据
* @return
*/
List<Employee> getAllData_m();
/**
* 获得已入职数据
* @return
*/
List<Employee> getPutData_m();
/**
* 入职
* @param params
* @return
*/
Integer putOnEmployee_m(@Param("emp_nos")ArrayList<String> params);
/**
* 离职
* @param params
* @return
*/
Integer putDownEmployee_m(@Param("emp_nos")ArrayList<String> params);
}
mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 根标签 -->
<mapper namespace="com.lzl.mapper.EmployeeMapper">
<!-- 开启二级缓存 设置缓存实现类-->
<cache/>
<!-- id是全局引用的唯一标识 type是指定的实体类名 可以是别名-->
<resultMap id="empMap" type="employee">
<!-- property是实体类属性 column是数据库列名 -->
<!-- id标注主键列 -->
<!-- result标注普通列-->
<id property="emp_no" column="emp_no" jdbcType="INTEGER"/>
<result property="emp_name" column="emp_name" jdbcType="VARCHAR"/>
<result property="emp_gender" column="emp_gender" jdbcType="VARCHAR"/>
<result property="emp_age" column="emp_age" jdbcType="INTEGER"/>
<result property="emp_dept_no" column="emp_dept_no" jdbcType="INTEGER"/>
<result property="emp_salary" column="emp_salary" jdbcType="DOUBLE"/>
<result property="emp_hire_time" column="emp_hire_time" jdbcType="VARCHAR"/>
<result property="emp_position" column="emp_position" jdbcType="VARCHAR"/>
<result property="emp_status" column="emp_status" jdbcType="INTEGER"/>
<!-- 映射多类合作 普通属性可以不用指定jdbcType 此处指定的是javaType 必须指定-->
<association property="department" javaType="department">
<id column="dept_no" property="dept_no"/>
<result column="dept_name" property="dept_name"/>
</association>
</resultMap>
<!-- 注意在<select>元素中,不能同时使用 resultMap 和 resultType 属性。-->
<select id="getAll" resultMap="empMap">
select e.*,d.dept_no,d.dept_name from employee e
inner join department d on e.emp_dept_no = d.dept_no
<where>
<if test="emp_name !=null and emp_name !=''">
and e.emp_name like "%"#{emp_name}"%"
</if>
<if test="dept_no !=null and dept_no !=''">
and e.emp_dept_no = #{dept_no}
</if>
<if test="emp_status !=null and emp_status !=''">
and e.emp_status = #{emp_status}
</if>
<if test="begin !=null and begin !=''">
and e.emp_hire_time >= #{begin}
</if>
<if test="end !=null and end !=''">
and e.emp_hire_time <= #{end}
</if>
</where>
order by e.emp_no
limit #{page},#{limit}
</select>
<select id="getCount" resultType="Integer">
select count(*) from employee e
inner join department d on e.emp_dept_no = d.dept_no
<where>
<if test="emp_name !=null and emp_name !=''">
and e.emp_name like "%"#{emp_name}"%"
</if>
<if test="dept_no !=null and dept_no !=''">
and e.emp_dept_no = #{dept_no}
</if>
<if test="emp_status !=null and emp_status !=''">
and e.emp_status = #{emp_status}
</if>
<if test="begin !=null and begin !=''">
and e.emp_hire_time >= #{begin}
</if>
<if test="end !=null and end !=''">
and e.emp_hire_time <= #{end}
</if>
</where>
</select>
<!--
/**
* foreach 多个id查询
* 传入参数是List集合
*/
List<Book> getBookByForeach(@Param("ids") List<Integer> ids);
<foreach collection="ids" item="id"-->
<!-- open="(" close=")" separator=",">-->
<!-- #{id}-->
<!--</foreach>-->
<!--如何获取自增主键的值:
useGeneratedKeys="true" 告诉mybatis获取自增主键的值
keyColumn: 来自于表的对应列
keyProperty:要存到实体类的属性
可以把获取的自增主键的值 反向存储到传入的实体类的对应属性中-->
<insert id="addNew" useGeneratedKeys="true" keyColumn="emp_no" keyProperty="emp_no">
insert into employee(emp_name,emp_gender,emp_age,emp_dept_no,emp_salary,
emp_hire_time,emp_position)
values(#{emp_name},#{emp_gender},#{emp_age},#{emp_dept_no},#{emp_salary},
#{emp_hire_time},#{emp_position});
</insert>
<update id="updateInfo">
update employee
<set>
<if test="emp_name != null and emp_name != '' ">
emp_name = #{emp_name},
</if>
<if test="emp_gender != null and emp_gender != '' ">
emp_gender = #{emp_gender},
</if>
<if test="emp_age != null and emp_age != '' ">
emp_age = #{emp_age},
</if>
<if test="emp_dept_no != null and emp_dept_no != '' ">
emp_dept_no = #{emp_dept_no},
</if>
<if test="emp_salary != null and emp_salary != '' ">
emp_salary = #{emp_salary},
</if>
<if test="emp_position != null and emp_position != '' ">
emp_position = #{emp_position},
</if>
<if test="emp_status != null and emp_status != '' ">
emp_status = #{emp_status},
</if>
</set>
where emp_no = #{emp_no}
</update>
<delete id="deleteInfoByEmp_no">
delete from employee where emp_no in
<foreach collection="emp_nos" item="emp_no"
open="(" close=")" separator=",">
#{emp_no}
</foreach>
</delete>
<select id="getAllData_m" resultType="employee">
select emp_no,emp_name from employee;
</select>
<select id="getPutData_m" resultType="employee">
select emp_no,emp_name from employee where emp_status = 0;
</select>
<update id="putOnEmployee_m">
update employee set emp_status = 0 where emp_no in
<foreach collection="emp_nos" item="emp_no"
open="(" close=")" separator=",">
#{emp_no}
</foreach>
</update>
<update id="putDownEmployee_m">
update employee set emp_status = 1 where emp_no in
<foreach collection="emp_nos" item="emp_no"
open="(" close=")" separator=",">
#{emp_no}
</foreach>
</update>
</mapper>
测试运行
看到已经实现了显示所有和分页展示,证明我们已经将SSM整合成功
总结
在整合中的最大问题就是配置文件的编写和注解的使用,配置文件的编写需要理解每个部分(SSM)在没整合之前干的是哪些事,整合之后,这个事谁来干,这样能保证配置项不会漏掉。