使用注解配置mybatis
注解VS XML
XML:
优点:入门容易;可以实现非常复杂的配置;避免硬编码;可以配置第三方的类;
缺点:编码效率比较低
注解:
优点:开发效率高
缺点:不好理解(记);复杂功能实现不了或者非常麻烦;存在硬编码;不可以在第三方的代码(class)中使用注解;
mybatis的常用注解
@Select@Insert@Update@Delete
@Results@Result
@Many@One
综合案例(javaweb)
员工信息的增删改查
step1、准备数据
use ee121;
create table emp (
id int (11) primary key AUTO_INCREMENT,
ename varchar (150),
joindate date ,
salary Decimal (9),
bonus Decimal (9),
dept_id int (11)
);
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1001','张德华','2000-12-17','8000.00',NULL,'20');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1002','传园慧','2001-02-20','16000.00','3000.00','30');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1003','向雯娜','2001-02-22','12500.00','5000.00','30');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1004','双超','2001-04-02','29750.00',NULL,'20');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1005','孔俪','2001-09-28','12500.00','14000.00','30');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1006','木子晨','2001-05-01','28500.00',NULL,'30');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1007','双紫棋','2001-09-01','24500.00',NULL,'10');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1008','茳冰冰','2007-04-19','30000.00',NULL,'20');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1009','王祖红','2001-11-17','50000.00',NULL,'10');
insert into emp (id, ename, joindate, salary, bonus, dept_id) values('1010','染静如','2001-09-08','15000.00','0.00','30');
step2、建立模块并搭建开发环境
step3、拷贝jar包
数据库驱动
mybatis
log4j
beanutils.jar logging.jar
step4、建立实体类
step5、建立mybatis的配置文件
查看所有员工
step1、流程图
step2、编写Servlet
step3、编写Service接口和实现类
可以直接拷贝mybatis的工具类
step4、dao接口和映射文件
step5、单元测试
step6、编写页面即可
a、导入jstl的标签库
b、编写页面
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>员工列表</title>
</head>
<body>
<h2>员工列表</h2>
<table border="1" width="78%">
<tr>
<th>序号</th>
<th>姓名</th>
<th>入职日期</th>
<th>月薪</th>
<th>奖金</th>
<th>部门编号</th>
<th>操作</th>
</tr>
<c:forEach items="${emps}" var="emp" varStatus="vs">
<tr style="background-color: ${vs.index%2==0?'#c3f3c3':'#f3c3f3'}">
<td>${vs.count}</td>
<td>${emp.ename}</td>
<td>${emp.joindate}</td>
<td>${emp.salary}</td>
<td>${emp.bonus}</td>
<td>${emp.deptId}</td>
<td>
<a href="">修改</a>
<a href="">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
step7、改进一下默认主页
step8、展现效果
添加员工信息
step1、编写一个post请求参数中文过滤器
package com.itheima.web.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//编码参数可配置的
public class CharacterEncodingFilter implements Filter {
private String encoding = "GBK";//默认编码
public void init(FilterConfig filterConfig) throws ServletException {
//读取参数encoding,如果有值,覆盖默认编码
String encoding = filterConfig.getInitParameter("encoding");
if(encoding!=null)
this.encoding = encoding;
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)servletRequest;
response = (HttpServletResponse)servletResponse;
}catch (Exception e){
throw new ServletException("non-http request or response");
}
//获取请求方式
String method = request.getMethod();
if("post".equalsIgnoreCase(method)) {
//设置请求的编码
request.setCharacterEncoding(encoding);
}
//放行
filterChain.doFilter(request,response);
}
public void destroy() {
}
}
step2、配置过滤器
<?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_3_1.xsd"
version="3.1">
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.itheima.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>
</web-app>
step3、修改listEmps.jsp
step4、添加页面
step5、servlet
step6、编写业务代码
step7、dao和映射文件
step8、测试
修改员工信息
step1、修改列表页面
step2、Servlet
step3、业务层代码
step4、dao和映射文件
step5、editEmp.jsp
step6、编写EditEmpServlet
step7、业务层代码
step8、dao接口和映射文件
删除员工信息:删除1个,批量删除
删除1个
step1、修改listEmps。jsp
step2、编写Servlet
step3、业务层
step4、持久层
step5、测试即可
删除多个
step1、修改页面listEmps.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>员工列表</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<h2>员工列表</h2>
<a href="${pageContext.request.contextPath}/addEmp.jsp">添加</a>
<a href="javascript:toDelMore()">删除</a>
<hr/>
<form id="f1" method="post" action="${pageContext.request.contextPath}/delMoreServlet">
<table border="1" width="78%">
<tr>
<th>选择</th>
<th>序号</th>
<th>姓名</th>
<th>入职日期</th>
<th>月薪</th>
<th>奖金</th>
<th>部门编号</th>
<th>操作</th>
</tr>
<c:forEach items="${emps}" var="emp" varStatus="vs">
<tr style="background-color: ${vs.index%2==0?'#c3f3c3':'#f3c3f3'}">
<td><input type="checkbox" name="ids" value="${emp.id}"> </td>
<td>${vs.count}</td>
<td>${emp.ename}</td>
<td>${emp.joindate}</td>
<td>${emp.salary}</td>
<td>${emp.bonus}</td>
<td>${emp.deptId}</td>
<td>
<a href="${pageContext.request.contextPath}/editEmpUIServlet?eid=${emp.id}">修改</a>
<a href="javascript:toDelOne(${emp.id})">删除</a>
</td>
</tr>
</c:forEach>
</table>
</form>
<script type="text/javascript">
function toDelMore() {
//是否选择了
var selectedIdsLength = $("#f1 input[name='ids']:checked").length;
if(selectedIdsLength==0){
alert("请先选择要删除的记录");
return;
}
var sure = confirm("确定要删除吗");
if(sure)
$("#f1").submit();
}
/*function toDelMore() {//原始的JS代码
//是否选择了
var ids = document.getElementsByName("ids");
var selected = false;//选择标志
//没有选择:提示
for(var i=0;i<ids.length;i++){
if(ids[i].checked){
selected = true;
break;//跳出循环
}
}
if(!selected){
alert("请先选择要删除的记录");
return;
}
//选择了:提示确定是否删除
var sure = confirm("确定要删除吗");
if(sure)
document.getElementById("f1").submit();
//确定:提交表单
}*/
function toDelOne(empId){
var sure = confirm("确定要删除吗");
if(sure)
location.href="${pageContext.request.contextPath}/delOneServlet?empid="+empId;
}
</script>
</body>
</html>
step2、编写Servlet
step3、业务层
step4、持久层
分页查询:(难点)
step1、编写一个封装了所有分页信息的类
package com.itheima.commons;
import java.util.List;
//封装所有与分页有关的数据
public class PageBean {
private List records;//显式的分页记录
private int pageNum;//当前页码
private int totalRecords;//总记录条数
private int totalPageNum;//总页数
private int pageSize = 5;//每页显式的记录条数
private int prePageNum;//上一页
private int nextPageNum;//下一页
private int startIndex;//每页开始记录的索引
private int startPageNum;
private int endPageNum;
public PageBean(int pageNum,int totalRecords){
this.pageNum = pageNum;
this.totalRecords = totalRecords;
//总页数
totalPageNum = totalRecords%pageSize==0?totalRecords/pageSize:totalRecords/pageSize+1;
//上一页
prePageNum = pageNum-1<1?1:pageNum-1;
//下一页
nextPageNum = pageNum+1>totalPageNum?totalPageNum:pageNum+1;
//每页开始记录的索引
startIndex = (pageNum-1)*pageSize;
//计算开始和结束页码
if(totalPageNum<=10){
startPageNum = 1;
endPageNum = totalPageNum;
}else{
startPageNum = pageNum-5;
endPageNum = pageNum+4;
if(startPageNum<1){
startPageNum = 1;
endPageNum = 10;
}
if(endPageNum>=totalPageNum){
endPageNum = totalPageNum;
startPageNum = endPageNum-9;
}
}
}
public int getStartPageNum() {
return startPageNum;
}
public void setStartPageNum(int startPageNum) {
this.startPageNum = startPageNum;
}
public int getEndPageNum() {
return endPageNum;
}
public void setEndPageNum(int endPageNum) {
this.endPageNum = endPageNum;
}
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public List getRecords() {
return records;
}
public void setRecords(List records) {
this.records = records;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getTotalPageNum() {
return totalPageNum;
}
public void setTotalPageNum(int totalPageNum) {
this.totalPageNum = totalPageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPrePageNum() {
return prePageNum;
}
public void setPrePageNum(int prePageNum) {
this.prePageNum = prePageNum;
}
public int getNextPageNum() {
return nextPageNum;
}
public void setNextPageNum(int nextPageNum) {
this.nextPageNum = nextPageNum;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
}
step2、编写持久层代码
step3、映射文件
step4、业务接口
step5、业务实现
step6、修改Servlet
step7、修改listEmp.jsp
step8、进一步修改
insert into emp (ename) values('a');//多插入几条
step9、改造PageBean
step10、改造listEmps.jsp