今天我们来回顾下Mybatis的基本使用和配置,这篇博客我们着重讲下怎么配置和使用的,若有读者想去研究mybatis的高级进阶-批处理和注解配置,请访问我之前写的两篇博客。
mybatis高级进阶☞批处理 https://juejin.im/post/5dc6bc565188251ab9183c6b
mybatis基于注解方式实现增删改查 https://juejin.im/post/5dc6acc75188255927494bc0
1、Mybatis的基本配置
第一步:导入mybatis和mysql的相关依赖
第二步:在src目录下配置mybatis主配置环境mybatisConfig.xml
-
1、引入mybatis-config.dtd的配置文件头部
-
2、配置configuration环境
- typeAliases 给实体类起别名,简化mapper.xml中对实体类的写法(注意:优先级比较高,放在最前面)
- environment中配置事务管理器、数据库连接池、数据库的四大参数、连接数
- mappers中配置mapper.xml的地址路径(注意:以/分割)
<?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>
<!--
给实体类起别名,为了mapper.xml中使用实体类时简便写法
type: 实体类的全路径名称
alias: 别名,起的别名和mapper.xml中resultMap中的一致
-->
<typeAliases>
<typeAlias type="com.yueqian.mgrEmp.model.entity.EmpEntity" alias="EmpEntity"/>
<typeAlias type="com.yueqian.mgrEmp.model.entity.DeptEntity" alias="DeptEntity"/>
</typeAliases>
<!--配置mybatisd的环境,包括事务,数据库连接四大参数,连接池的连接数 -->
<environments default="empsMysql">
<environment id="empsMysql">
<!-- 配置事务管理器 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据库连接池 -->
<dataSource type="POOLED">
<!-- 配置url -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/emps?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="6831245"/>
<!-- –最大活动连接数。默认值:10 -->
<property name="poolMaximumActiveConnections" value="20"/>
<!-- –最大空闲连接数。 -->
<property name="poolMaximumIdleConnections" value="1"/>
<!-- –池中连接的检查时间。默认值:20000毫秒 -->
<property name="poolMaximumCheckoutTime" value="60000"/>
</dataSource>
</environment>
</environments>
<!-- 配置mapper.xml的地址 -->
<mappers>
<mapper resource="com/yueqian/mgrEmp/model/mapper/EmpMapper.xml"/>
<mapper resource="com/yueqian/mgrEmp/model/mapper/DeptMapper.xml"/>
</mappers>
</configuration>
第三步:编写实体类
public class EmpEntity {
private Integer empNo;
private String eName;
private String job;
private Integer mgr;
private Date hiredate;
private Double sal;
private Double comm;
private DeptEntity dept;
}
第四步:编写mapper接口
package com.yueqian.mgrEmp.model.mapper;
import java.util.List;
import java.util.Map;
import com.yueqian.mgrEmp.model.entity.EmpEntity;
public interface EmpMapper {
/**
* 查询所有员工信息
*/
List<EmpEntity> getEmps(Map<String,Object> param);
/**
* 查询单个员工信息
*/
EmpEntity getEmpById(Integer id);
/**
* 添加员工信息
*/
int insertEmp(EmpEntity empEntity);
/**
* 删除员工信息
*/
int delEmp(Integer id);
/**
* 修改员工信息
*/
Integer updateEmp(EmpEntity empEntity);
/**
* 查询所有工作
*/
List<String> getJobs();
/**
* 查询最大员工编号
*/
Integer getNewNum();
}
第五步:编写mapper.xml,使实体类与数据库相互映射
-
1、配置mybatis.dtd的头部文件
-
2、配置mapper
-
namespace:配置接口全路径类名
-
select: 查询
- id:代表mapper接口的具体方法名(通过全路径接口名和方法名映射具体实现的方法)
- resultType:代表方法返回的类型,基本类型小写表示,实体类型首字母大写表示
- resultMap: 代表实体类和实体类之间的映射关系(比如疫情数据实体类里面嵌套用户实体类,type:代表实体类全路径类名,起了别名后,就使用别名表示,id代表映射的名称标识,和association中的resultMap值对应)
- association 表示多对一关系(property代表实体类嵌套封装的实体类名称,resultMap中的值对应的是上面产生映射关系的id名称)
- parameterType 表示参数类型,基本类型小写表示,实体类型首字母大写表示
-
insert 添加
-
delete 删除
-
update 修改
添加、删除、修改返回的resultType返回的默认是int类型,可以不写
-
<?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.yueqian.mgrEmp.model.mapper.EmpMapper">
<resultMap type="DeptEntity"
id="deptMap">
<id column="deptno" property="deptno" />
<result column="dname" property="dname" />
<result column="loc" property="loc" />
</resultMap>
<resultMap type="EmpEntity"
id="empMapper">
<id property="empNo" column="EMPNO" />
<result property="eName" column="ENAME" />
<result property="job" column="JOB" />
<result property="mgr" column="MGR" />
<result property="hiredate" column="HIREDATE" />
<result property="sal" column="SAL" />
<result property="comm" column="COMM" />
<!-- 多对一关系 多个员工对应一个部门 -->
<!-- 方式一:在resultMap中内嵌 association,使用javaType属性 -->
<!-- <association property="dept" javaType="com.yueqian.mgrEmp.model.entity.DeptEntity">
<id column="deptno" property="deptno"/> <result column="dname" property="dname"/>
<result column="loc" property="loc"/> </association> --> <!-- 方式二:将resultMap分离 -->
<association property="dept" resultMap="deptMap"></association>
</resultMap>
<!-- 查询所有员工信息 -->
<select id="getEmps" resultMap="empMapper"
parameterType="map">
SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, d.DEPTNO, d.loc,
d.dname FROM emp e, dept d
where d.deptno = e.deptno
<if test="contection != null">
and
EMPNO like #{contection} or
ENAME like #{contection} or
JOB like #{contection} or
MGR like #{contection} or
SAL like #{contection} or
COMM like #{contection}
</if>
order by ${colName} desc
</select>
<!-- 查询所有工作 -->
<select id="getJobs" resultType="string">
SELECT DISTINCT job FROM emp
</select>
<!-- 查询最大员工账号 -->
<select id="getNewNum" resultType="int">
SELECT MAX(IFNULL (empno,0))+1
maxnum FROM emp
</select>
<!-- 如果添加员工时,每次都需要先查询id,再添加员工,太麻烦,如果在添加时不需要两步,需要两种方式配置,选择其一即可 如果我们的数据库是自增主键,直接insert标签就可以添加进数据库,但是自增id不能让前端获取到,必须设置keyProperty属性,将查询的自增主键传到前端
方式一:insert中配置两个属性 useGeneratedKeys="true" 表示开启自动增长 keyProperty="empNo" 表示自增长的属性
方式二:insert中内嵌select标签,查询最大账号,其中有 order属性:表示查询在添加前执行 keyProperty属性:表示查询的结果集给设定的主键属性
一定只能返回一个值 resultType属性:表示查询结果返回的类型 -->
<!-- 添加员工 -->
<!-- jdbcType=DATE 表示当传入的值为null时,将null值表示为指定类型的空串 -->
<!-- <insert id="insertEmp" parameterType="com.yueqian.mgrEmp.model.entity.EmpEntity"
useGeneratedKeys="true" keyProperty="empNo"> -->
<insert id="insertEmp"
parameterType="EmpEntity">
<selectKey order="BEFORE" keyProperty="empNo"
resultType="int">
SELECT MAX(IFNULL (empno,0))+1 maxnum FROM emp
</selectKey>
INSERT INTO emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
VALUES(#{empNo}, #{eName}, #{job}, #{mgr}, #{hiredate, jdbcType=DATE},
#{sal}, #{comm}, #{dept.deptno})
</insert>
<!-- 删除员工信息 -->
<delete id="delEmp" parameterType="int">
delete from emp where empno =
#{empNo}
</delete>
<!-- 按编号查询员工信息 -->
<select id="getEmpById"
resultType="EmpEntity"
parameterType="int">
SELECT EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO FROM
emp WHERE EMPNO = #{empNo}
</select>
<!-- 修改员工信息 -->
<update id="updateEmp"
parameterType="EmpEntity">
UPDATE emp SET
ENAME=#{eName},JOB=#{job},MGR=#{mgr},HIREDATE=#{hiredate},SAL=#{sal},COMM=#{comm},DEPTNO=#{dept.deptno}
WHERE EMPNO = #{empNo}
</update>
</mapper>
第六步:编写service层
package com.yueqian.mgrEmp.service;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.yueqian.mgrEmp.model.entity.EmpEntity;
import com.yueqian.mgrEmp.model.mapper.EmpMapper;
import com.yueqian.mgrEmp.utils.DBUtils;
public class EmpService {
// 单例模式
private static EmpService empService;
private EmpService() {
}
public static EmpService getInstance() {
if (empService == null) {
empService = new EmpService();
}
return empService;
}
/**
* 查询所有员工信息
*
* @throws IOException
*/
public List<EmpEntity> getEmps(String contection) throws IOException {
// 定义代理对象 mapper
EmpMapper mapper = null;
// 定义空集合列表 注意此集合列表不能对集合增删操作,否则报错
List<EmpEntity> allEmps = Collections.EMPTY_LIST;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession对象获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper对象操作数据库
//判断传过来模糊查询的参数是否为null
if(contection != null) {
contection = "%"+contection+"%";
}
Map<String,Object> param = new HashMap<String,Object>();
param.put("contection", contection);
param.put("colName", "empno");
allEmps = mapper.getEmps(param);
// 提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return allEmps;
}
/**
* 查询所有工作
*
* @throws IOException
*/
public List<String> getJobs() throws IOException {
// 定义查询集合
List<String> jobList = null;
// 定义mapper代理对象
EmpMapper mapper = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper代理对象操作数据库
jobList = mapper.getJobs();
// 成功提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 失败回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return jobList;
}
/**
* 查询单个员工信息
* @throws IOException
*/
public EmpEntity getEmpById(Integer id) throws IOException {
// 定义代理对象 mapper
EmpMapper mapper = null;
//定义返回的员工对象
EmpEntity entity = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession对象获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper对象操作数据库
entity = mapper.getEmpById(id);
// 提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return entity;
}
/**
* 添加员工信息
*
* @throws IOException
*/
public boolean insertEmp(EmpEntity empEntity) throws IOException {
int count = 0;
// 定义mapper代理对象
EmpMapper mapper = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
// 因为从前端页面获取的数据没有编号,此时从数据库查询最大编号赋给对象
//empEntity.setEmpNo(this.getNewNum());
try {
// 通过sqlSession获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper代理对象操作数据库
count = mapper.insertEmp(empEntity);
// 成功提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 失败回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return count > 0 ? true : false;
}
/**
* 查询最大员工账号
*
* @throws IOException
*/
public Integer getNewNum() throws IOException {
Integer count = 0;
// 定义mapper代理对象
EmpMapper mapper = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper代理对象操作数据库
count = mapper.getNewNum();
// 成功提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 失败回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return count;
}
/**
* 删除员工信息
*
* @throws IOException
*/
public boolean delEmp(Integer id) throws IOException {
int count = 0;
// 定义mapper代理对象
EmpMapper mapper = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper代理对象操作数据库
count = mapper.delEmp(id);
// 成功提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 失败回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return count > 0 ? true : false;
}
/**
* 修改员工信息
* @throws IOException
*/
public boolean updateEmp(EmpEntity empEntity) throws IOException {
Integer count = 0;
// 定义mapper代理对象
EmpMapper mapper = null;
// 获取sqlSession对象
SqlSession sqlSession = DBUtils.getSession();
try {
// 通过sqlSession获取mapper代理对象
mapper = sqlSession.getMapper(EmpMapper.class);
// 通过mapper代理对象操作数据库
count = mapper.updateEmp(empEntity);
// 成功提交事务
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 失败回滚事务
sqlSession.rollback();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return count > 0 ? true : false;
}
}
第七步:编写servlet
package com.yueqian.mgrEmp.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yueqian.mgrEmp.model.entity.DeptEntity;
import com.yueqian.mgrEmp.model.entity.EmpEntity;
import com.yueqian.mgrEmp.service.DeptService;
import com.yueqian.mgrEmp.service.EmpService;
@WebServlet("/EmpServlet")
public class EmpServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 格式化时间
private SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
public EmpServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取前端传递的请求路径参数
String queryURI = request.getParameter("queryURI");
if ("addEmp".equals(queryURI)) {
// 添加员工
try {
addEmp(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if ("delEmp".equals(queryURI)) {
delEmp(request, response);
} else if ("selEmpById".equals(queryURI)) {
// 修改前查询
selEmpById(request, response);
} else if ("updateEmp".equals(queryURI)) {
updateEmp(request, response);
} else if("queryAll".equals(queryURI)){
// 带模糊方式查询员工
queryEmp(request, response);
}else {
// 查询员工
queryEmp(request, response);
}
}
/**
* 修改员工信息
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void updateEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取前端传递的参数
String empNoStr = request.getParameter("empNo");
System.out.println("============"+empNoStr);
int empNo = 0;
if(empNoStr != null && empNoStr.trim().length() != 0) {
try {
empNo = Integer.parseInt(empNoStr);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String empName = request.getParameter("empName");
if (empName == null || empName.trim().equals("")) {
this.error2RegMsg(request, response, "用户名不能为空!");
return;
}
String job = request.getParameter("job");
Integer mgr = 8888;
mgr = Integer.parseInt(request.getParameter("mgr"));
Date hiredate = new Date();
try {
String date = request.getParameter("hiredate");
if (date != null) {
hiredate = smf.parse(date);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double sal = 0;
sal = Double.parseDouble(request.getParameter("sal"));
double comm = 0;
comm = Double.parseDouble(request.getParameter("comm"));
Integer dept = 10;
dept = Integer.parseInt(request.getParameter("dept"));
// 封装到对象
EmpEntity empEntity = new EmpEntity();
empEntity.setEmpNo(empNo);
empEntity.seteName(empName);
empEntity.setJob(job);
empEntity.setMgr(mgr);
empEntity.setHiredate(hiredate);
empEntity.setSal(sal);
empEntity.setComm(comm);
DeptEntity deptEntity = new DeptEntity();
deptEntity.setDeptno(dept);
empEntity.setDept(deptEntity);
// 保存入库
if (EmpService.getInstance().updateEmp(empEntity)) {
// 注意,此时是插入数据操作,必须用重定向,如果用请求转发,就会插入两次
response.sendRedirect(request.getContextPath() + "/EmpServlet");
} else {
error2RegMsg(request, response, "服务器繁忙,请联系管理员。。。");
}
}
/**
* 按编号查询员工
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void selEmpById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取前端传递要修改的id
String empNoStr = request.getParameter("empNo");
Integer empNo = 7369;
if (empNoStr != null) {
empNo = Integer.parseInt(empNoStr);
}
// 返回查询的员工信息
EmpEntity empEntity = EmpService.getInstance().getEmpById(empNo);
// 获取所有员工
List<EmpEntity> empList = EmpService.getInstance().getEmps(null);
request.setAttribute("empList", empList);
// 获取所有工作
List<String> jobList = EmpService.getInstance().getJobs();
request.setAttribute("jobList", jobList);
// 获取所有部门信息
List<DeptEntity> deptList = DeptService.getInstance().getDepts();
request.setAttribute("deptList", deptList);
// 设置员工信息到request请求域中
request.setAttribute("empEntity", empEntity);
// 设置所有员工信息到请求域中
request.setAttribute("empList", empList);
// 设置所有工作信息到请求域中
request.setAttribute("jobList", jobList);
// 跳转到展示页面
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
/**
* 删除员工
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void delEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String empNo = request.getParameter("empNo");
if (empNo == null || empNo.trim().equals("")) {
this.error2IndexMsg(request, response, "删除编号不能为空");
return;
}
Integer id = 0;
try {
id = Integer.parseInt(empNo);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.error2IndexMsg(request, response, "需要正确删除员工的编号");
}
if (EmpService.getInstance().delEmp(id)) {
// 重定向到index页面
response.sendRedirect(request.getContextPath() + "/EmpServlet");
} else {
this.error2IndexMsg(request, response, "服务器繁忙,请稍后重试...");
return;
}
}
/**
* 添加员工
*
* @param request
* @param response
*/
private void addEmp(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取前端传递的参数
String empName = request.getParameter("empName");
if (empName == null || empName.trim().equals("")) {
this.error2RegMsg(request, response, "用户名不能为空!");
return;
}
String job = request.getParameter("job");
Integer mgr = 8888;
mgr = Integer.parseInt(request.getParameter("mgr"));
Date hiredate = new Date();
try {
String date = request.getParameter("hiredate");
if (date != null) {
hiredate = smf.parse(date);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double sal = 0;
sal = Double.parseDouble(request.getParameter("sal"));
double comm = 0;
comm = Double.parseDouble(request.getParameter("comm"));
Integer dept = 10;
dept = Integer.parseInt(request.getParameter("dept"));
// 封装到对象
EmpEntity empEntity = new EmpEntity();
empEntity.seteName(empName);
empEntity.setJob(job);
empEntity.setMgr(mgr);
empEntity.setHiredate(hiredate);
empEntity.setSal(sal);
empEntity.setComm(comm);
DeptEntity deptEntity = new DeptEntity();
deptEntity.setDeptno(dept);
empEntity.setDept(deptEntity);
// 保存入库
if (EmpService.getInstance().insertEmp(empEntity)) {
// 注意,此时是插入数据操作,必须用重定向,如果用请求转发,就会插入两次
response.sendRedirect(request.getContextPath() + "/EmpServlet");
} else {
error2RegMsg(request, response, "服务器繁忙,请联系管理员。。。");
}
}
/**
* 错误时跳转到注册页面
*
* @param request
* @param response
* @param errorMsg
* @throws ServletException
* @throws IOException
*/
private void error2RegMsg(HttpServletRequest request, HttpServletResponse response, String errorMsg)
throws ServletException, IOException {
// 设置错误消息
request.setAttribute("errorMsg", errorMsg);
// 跳转到登录界面
request.getRequestDispatcher("/InitAddEmpServlet").forward(request, response);
}
/**
* 错误时跳转到index页面
*
* @param request
* @param response
* @param errorMsg
* @throws ServletException
* @throws IOException
*/
private void error2IndexMsg(HttpServletRequest request, HttpServletResponse response, String errorMsg)
throws ServletException, IOException {
// 设置错误消息
request.setAttribute("errMsg", errorMsg);
// 跳转到登录界面
request.getRequestDispatcher("/EmpServlet").forward(request, response);
}
/**
* 查询员工
*
* @throws IOException
* @throws ServletException
*/
private void queryEmp(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String contection = request.getParameter("contection");
// 获取员工列表数据
List<EmpEntity> empList = EmpService.getInstance().getEmps(contection);
// 将数据设置到请求域中
request.setAttribute("empList", empList);
// 请求转发到展示页面
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第八步:编写jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- bootstrap对IE览器器的支持 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- bootstrap对各个平台的支持 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<!-- 引入bootstrap时要依赖的jquery -->
<script type="text/javascript" src="./js/jquery.min.js"></script>
<!-- 引入bootstrap的主css文件 -->
<link href="./bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- 引入bootstrap的主题样式 -->
<link href="./bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
<!-- 引入bootstrap的js -->
<script type="text/javascript" src="./bootstrap/js/bootstrap.min.js"></script>
<title>部门员工管理页面</title>
<script type="text/javascript">
$(function(){
if("${errorMsg}"){
$("#errorDialog").modal("show");
}
});
function delEmp()
{
var mymessage=confirm("你确定删除吗?");
if(mymessage==true)
{
document.write("删除成功");
}
else if(mymessage==false)
{
document.write("删除失败");
}
}
</script>
</head>
<body>
<!-- 导航栏开始 -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
aria-expanded="false">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">员工管理</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-right" action="./EmpServlet">
<input type="hidden" name="queryURI" value="queryAll">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name = "contection">
</div>
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</form>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- 导航栏结束 -->
<!-- 菜单开始 -->
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="panel-group" id="menu">
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#menu" href="#div1">
员工管理</a>
</h4>
</div>
<div id="div1" class="panel-collapse collapse in">
<div class="list-group">
<a href="#" class="list-group-item">浏览员工</a> <a
href="./InitAddEmpServlet" class="list-group-item">添加员工</a>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#menu"
href="#div2">部门管理</a>
</h4>
</div>
<div id="div2" class="panel-collapse collapse">
<div class="list-group">
<a href="#" class="list-group-item">浏览部门</a> <a href="#"
class="list-group-item">添加部门</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-9">
<ol class="breadcrumb">
<li><a href="#">会员服务</a></li>
<li><a href="#">积分服务</a></li>
<li><a href="#">酒水服务</a></li>
</ol>
<table class="table table-default table-striped">
<thead>
<tr>
<th>员工编号</th>
<th>员工姓名</th>
<th>工作</th>
<th>管理者编号</th>
<th>入职时间</th>
<th>员工工资</th>
<th>员工奖金</th>
<th>部门名称</th>
<th>编辑</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<c:forEach items="${empList}" var="emp">
<tr>
<td>${emp.empNo}</td>
<td>${emp.eName}</td>
<td>${emp.job}</td>
<td>${emp.mgr}</td>
<td><fmt:formatDate value="${emp.hiredate}"
pattern="yyyy-MM-dd" /></td>
<td>${emp.sal}</td>
<td>${emp.comm}</td>
<td>${emp.dept.dname}</td>
<td><a href="${pageContext.request.contextPath}/EmpServlet?queryURI=selEmpById&empNo=${emp.empNo}"><span
class="glyphicon glyphicon-pencil"></span></a> <a
href="${pageContext.request.contextPath}/EmpServlet?queryURI=delEmp&empNo=${emp.empNo}" onclick="delEmp()"><span
class="glyphicon glyphicon-trash"></span></a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
<!-- 模态框-->
<div class="modal fade" tabindex="-1" role="dialog" id="errorDialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">提示</h4>
</div>
<div class="modal-body">
<p>${errorMsg}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</body>
</html>
以上是通过编写员工管理系统对mybatis的基本使用做了进一步的讲解,以后在初步学习配置和使用mybatis时可以使用该配置模板。喜欢的小伙伴可以双击666,记得点赞👍+关注👉哦!