文章目录
前面写了个简单的登陆功能,这里就简单的实现一下crud。
dao层
实体
package com.example.student.entity;import java.util.Date;/**
* 学生信息表
*
* @author xiaotao
*/publicclassStudentDO{/**
* 主键
*/private String id;/**
* 姓名
*/private String name;/**
* 年龄
*/private Integer age;/**
* 性别
*/private String sex;/**
* 创建日期
*/private Date createTime;/**
* 更新时间
*/private Date updateTime;public StringgetId(){return id;}publicvoidsetId(String id){this.id= id;}public StringgetName(){return name;}publicvoidsetName(String name){this.name= name;}public IntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age= age;}public StringgetSex(){return sex;}publicvoidsetSex(String sex){this.sex= sex;}public DategetCreateTime(){return createTime;}publicvoidsetCreateTime(Date createTime){this.createTime= createTime;}public DategetUpdateTime(){return updateTime;}publicvoidsetUpdateTime(Date updateTime){this.updateTime= updateTime;}@Overridepublic StringtoString(){return"StudentDO{"+"id='"+ id+'\''+", name='"+ name+'\''+", age="+ age+", sex='"+ sex+'\''+", createTime="+ createTime+", updateTime="+ updateTime+'}';}}
访问对象
这里count接口是干什么的呢,其实是用来前端分页的。
我们前端使用表格来显示学生信息,但是我们几乎不会用表格的一页显示所有数据,所有需要分页,这里大致分服务器分页和客户端分页。
- 客户端分页:一次性加载所有数据,切换数据不会再请求服务器。
- 服务器分页:显示多少数据,请求多少数据。
我们这里采用服务器分页,count就是用来统计数据的总量。
为什么要有这个接口呢,当然是我们后面service会用到了。。。所以后面再讲。
count和getStudent的参数是用来传递搜索信息的,这里我们搜索就放在数据库了,所以你在其他层是看不到搜索相关代码的。
package com.example.student.dao;import com.example.student.entity.StudentDO;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param;import java.util.List;import java.util.Map;/**
* 学生DAO接口
*
* @author xiaotao
*/@MapperpublicinterfaceStudentDAO{/**
* 获得学生信息数据的数量
*
* @param params 过滤参数
* @return 学生的数量
*/intcount(Map<String, Object> params);/**
* 获取学生信息
*
* @param params 过滤参数
* @return 学生信息主表链表
*/
List<StudentDO>getStudent(Map<String, Object> params);/**
* 插入一条记录
*
* @param studentDO 实体
*/voidinsert(StudentDO studentDO);/**
* 删除
*
* @param id 主键
*/voiddelete(@Param("id") String id);/**
* 修改客户信息
*
* @param studentDO 实体信息
*/voidupdate(StudentDO studentDO);}
xml文件
这里搜索就只搜索了name一个字段。
getStudent里面ORDER BY ${sort} ${order}
用来按照字段排序,LIMIT #{offset}, #{limit}
用来分页的,选取我们需要的数据。
insert里面selectKey可以自动生成id。
<?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"><mappernamespace="com.example.student.dao.StudentDAO"><resultMapid="StudentDO"type="com.example.student.entity.StudentDO"><idcolumn="id"property="id"jdbcType="VARCHAR"/><resultcolumn="name"property="name"/><resultcolumn="age"property="age"/><resultcolumn="sex"property="sex"/><resultcolumn="create_time"property="createTime"/><resultcolumn="update_time"property="updateTime"/></resultMap><selectid="count"resultType="java.lang.Integer">
SELECT count(*)
FROM `t_student`<where><iftest="name != null"> AND `name` LIKE CONCAT('%', #{name ,jdbcType=VARCHAR}, '%')</if></where></select><selectid="getStudent"resultMap="StudentDO">
SELECT *
FROM `t_student`<where><iftest="name != null"> AND `name` LIKE CONCAT('%', #{name ,jdbcType=VARCHAR}, '%')</if></where><choose><whentest="sort != null and sort.trim() !=''">
ORDER BY ${sort} ${order}</when></choose><iftest="offset != null and limit != null">
LIMIT #{offset}, #{limit}</if></select><insertid="insert"parameterType="com.example.student.entity.StudentDO"><selectKeykeyProperty="id"resultType="String"order="BEFORE">
SELECT replace(uuid(),'-','') FROM dual;</selectKey>
INSERT INTO `t_student` (`id`, `name`, `age`, `sex`, `create_time`, `update_time`)
VALUES (#{id}, #{name}, #{age}, #{sex}, now(), now())</insert><deleteid="delete">
DELETE FROM `t_student`
WHERE `id` = #{id};</delete><updateid="update"parameterType="com.example.student.entity.StudentDO">
UPDATE `t_student`
SET `name` = #{name},
`age` = #{age},
`sex` = #{sex},
`update_time` = now()
WHERE `id` = #{id};</update></mapper>
测试
尽管测试很简单,只是判断一下代码写的成不成功,但是也不能忽略。
package com.example.student.dao;import com.example.student.entity.StudentDO;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;import java.util.List;importstatic org.junit.jupiter.api.Assertions.assertEquals;importstatic org.junit.jupiter.api.Assertions.assertNotNull;@SpringBootTestclassStudentDAOTest{@Resourceprivate StudentDAO studentDAO;@TestvoidtestCount(){assertEquals(1, studentDAO.count(null));}@TestvoidtestGetStudent(){
List<StudentDO> result= studentDAO.getStudent(null);assertNotNull( result);
result.forEach( System.out::println);}@TestvoidtestInsert(){
StudentDO studentDO=newStudentDO();
studentDO.setName("xxx");
studentDO.setAge(10);
studentDO.setSex("男");
studentDAO.insert(studentDO);}@TestvoidtestDelete(){
studentDAO.delete("b4de711f900c11ea8fc654e1ad394a4a");}@TestvoidtestUpdate(){
StudentDO studentDO=newStudentDO();
studentDO.setId("b4de711f900c11ea8fc654e1ad394a4a");
studentDO.setName("yyy");
studentDO.setAge(20);
studentDO.setSex("女");
studentDAO.update(studentDO);}}
添加学生展示页面
添加插件
Bootstrap-table 显示表格
sweetalert 提示框(稍微好看点)
jquery-ui 拖动模态框等效果
插件具体如何使用可以去官网查看,这里只用最简单的一些功能。
添加一些js功能
- 初始化表格
- 弹出对话框
- 提示框样式修改
- ajax请求封装
- 时间格式化
- 模态框居中和拖拽功能
/**
* 渲染表格要用到的常用代码封装
*/// 初始化表格functioninitTable(node, url, pageList, queryParams, columns, toolbar='#toolbar'){
node.bootstrapTable("destroy");// 先销毁用来的表格再构造新的表格
node.bootstrapTable({
toolbar: toolbar,// 工具按钮用哪个容器
method:'get',// 请求方式
url: url,// 请求路径
dataType:"json",// 服务器返回的数据类型
contentType:"application/json",// 发送到服务器的数据编码类型
striped:true,// 是否显示行间隔色
cache:false,// 是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination:true,// 是否显示分页(*)
sortable:false,// 是否启用排序
sortOrder:"asc",// 排序方式
sidePagination:"server",// 分页方式:client客户端分页,server服务端分页(*)
queryParamsType:"limit",// 设置为 ‘limit’ 则会发送符合 RESTFul 格式的参数
pageNumber:1,// 初始化加载第一页,默认第一页
pageSize:10,// 每页的记录行数(*)
pageList: pageList,// 可供选择的每页的行数(*)
showColumns:true,// 是否显示所有的列
showRefresh:true,// 是否显示刷新按钮
minimumCountColumns:2,// 最少允许的列数
clickToSelect:true,// 是否启用点击选中行
showToggle:true,// 是否显示详细视图和列表视图的切换按钮
cardView:false,// 是否显示详细视图
detailView:false,// 是否显示父子表
uniqueId:"id",// 每一行的唯一标识,一般为主键列
dataField:"rows",// 这是返回的json数组的key.默认好像是"rows".这里只要前后端约定好就行
queryParams: queryParams,
responseHandler: result=>{if(result.success===false){switch(result.code){case9001:swal("错误","数据库错误","error");break;case9002:swal("错误","参数错误","error");break;case9999:swal("错误","系统错误","error");break;}returnnull;}else{return{ total: result.module.total, rows: result.module.rows,};}},
columns: columns,
rowStyle:function(row, index){let classesArr=['info','#ffffff'];let strClass="";if(index%2===0){// 偶数行
strClass= classesArr[0];}else{// 奇数行
strClass= classesArr[1];}return{ classes: strClass};}// 隔行变色});}// 弹出框functiondialog(message, callback){swal(message,{
buttons:{true:"确定",
cancel:"取消"},}).then((value)=>{switch(value){case"true":callback();break;default:break;}});}// 修改提示框样式functionchangeToolTip(){$(function(){$( document).tooltip({
position:{
my:"center bottom-20",
at:"center top",
using:function( position, feedback){$(this).css( position);$("<div>").addClass("arrow").addClass( feedback.vertical).addClass( feedback.horizontal).appendTo(this);}},
show:{
effect:"slideDown",
delay:250},
hide:{
effect:"explode",
delay:250}});$("select").on("select2:close",()=>$("[role=tooltip]").remove());});}// 无参数请求functionnoParameterPostRequest(url, callback, method="POST"){
$.ajax({
type: method,
url: url,
dataType:"json",
contentType:"application/json",
success:function(result){if(result.success===false){switch(result.code){case9001:swal("错误","数据库错误","error");break;case9002:swal("错误","参数错误","error");break;case9999:swal("错误","系统错误","error");break;}}else{callback(result);}},
error:function()