前端使用 Datatables + Bootstrap + JQuery,后台使用 SpringBoot + Mybatis
本代码旨在将 Datatables 的各个细节用法串联起来,因此前后端都没做非空验证。后台使用 SpringBoot + Mybatis,这里关于SpringBoot + Mybatis的整合就不详细说了,不懂的朋友可以参考:https://blog.csdn.net/wsjzzcbq/article/details/81563515
由于本文讲解的项目使用了本地静态资源,为方便大家学习,最后会将代码上传到码云,需要的朋友可以下载
效果演示如下图
效果图 1
效果图 2
1、数据库建表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`user_addr` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`create_date` datetime(0) NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
`role_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '宋江', '山东省郓城县', '2020-08-01 15:52:00', 1, 2);
INSERT INTO `user` VALUES (3, '卢俊义', '北京大名府', '2020-08-02 15:52:25', 1, 2);
INSERT INTO `user` VALUES (4, '吴用', '山东省菏泽市郓城县车市村人', '2020-08-03 15:52:27', 1, 2);
INSERT INTO `user` VALUES (5, '公孙胜', '蓟州人氏', '2020-08-04 15:52:30', 1, 1);
INSERT INTO `user` VALUES (7, '关胜', '河东解良(今山西运城)人', '2020-08-05 17:04:08', 1, 1);
INSERT INTO `user` VALUES (8, '林冲', '东京(河南开封)人氏', '2020-07-27 17:14:32', 1, 1);
INSERT INTO `user` VALUES (9, '呼延灼', '并州太原(今属山西太原)', '2020-08-07 09:15:56', 1, 1);
INSERT INTO `user` VALUES (10, '花荣', '山东青州清风镇', '2020-08-07 09:17:17', 1, 1);
INSERT INTO `user` VALUES (11, '秦明', '山后开州', '2020-08-07 09:18:00', 1, 1);
INSERT INTO `user` VALUES (12, '柴进', '沧州人氏', '2020-08-07 09:18:42', 1, 1);
INSERT INTO `user` VALUES (13, '李应', '郓州人氏', '2020-08-07 09:19:13', 1, 1);
INSERT INTO `user` VALUES (14, '朱仝', '郓城县人氏', '2020-08-07 09:28:57', 1, 1);
2、引入 maven 的 pom 依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.datatables.demo
datatables-demo
0.0.1-SNAPSHOT
datatables-demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
com.alibaba
fastjson
1.2.7
commons-lang
commons-lang
2.5
org.springframework.boot
spring-boot-devtools
runtime
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
3、配置 application.yml
server:
port: 80
spring:
datasource:
url: jdbc:mysql://192.168.0.110:3306/datatables_demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
config-location: classpath:mapper/config/sqlMapConfig.xml
logging:
level:
com.datatables.demo.mapper: debug
4、实体类
package com.datatables.demo.bean;
import com.datatables.demo.common.page.Page;
import java.util.Date;
public class User extends Page {
private Integer userId;
private String userName;
private String userAddr;
private Date createDate;
private Integer status;
private Integer roleId;
//日期范围查询条件
private String date;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAddr() {
return userAddr;
}
public void setUserAddr(String userAddr) {
this.userAddr = userAddr;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddr='" + userAddr + '\'' +
", createDate=" + createDate +
", status=" + status +
", roleId=" + roleId +
'}';
}
}
5、公共实体类
datatables 分页实体类
package com.datatables.demo.common.page;
public class Page {
private int draw;
private int offset;
private int pageSize;
public int getDraw() {
return draw;
}
public void setDraw(int draw) {
this.draw = draw;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
datatables 分页返回实体类
package com.datatables.demo.common.res;
/**
* datatables 接收实体类
*/
public class R {
public R() {
}
public R(int draw, int recordsTotal, int recordsFiltered, Object data) {
this.draw = draw;
this.recordsTotal = recordsTotal;
this.recordsFiltered = recordsFiltered;
this.data = data;
}
private int draw;
private int recordsTotal;
private int recordsFiltered;
private Object data;
public int getDraw() {
return draw;
}
public void setDraw(int draw) {
this.draw = draw;
}
public int getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(int recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
6、mapper 层
package com.datatables.demo.mapper;
import com.datatables.demo.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper {
//查询分页数据
List getUserList(RowBounds rowBounds, Map map);
//查询数据总条数
int getUserListCount(RowBounds rowBounds, Map map);
int insert(User user);
int delete(Integer userId);
User getById(Integer userId);
int updateById(User user);
}
mapper 层 xml 文件
user_id, user_name, user_addr, role_id
insert into user (user_name, user_addr, status,
role_id, create_date)
values ( #{userName,jdbcType=VARCHAR}, #{userAddr,jdbcType=VARCHAR},
#{status,jdbcType=INTEGER}, #{roleId,jdbcType=INTEGER}, #{createDate})
delete from user where user_id = #{userId}
update user
set user_name = #{userName,jdbcType=VARCHAR},
user_addr = #{userAddr,jdbcType=VARCHAR},
status = #{status},
role_id = #{roleId,jdbcType=INTEGER}
where user_id = #{userId,jdbcType=INTEGER}
7、service 层
package com.datatables.demo.service;
import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;
public interface UserService {
R getPageUserList(User user);
int insert(User user);
int delete(Integer userId);
User getById(Integer userId);
int updateById(User user);
}
serviceimpl 层
package com.datatables.demo.service.impl;
import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;
import com.datatables.demo.mapper.UserMapper;
import com.datatables.demo.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public R getPageUserList(User user) {
//查询条件
Map searchCondition = new HashMap();
if(StringUtils.isNotBlank(user.getUserName())) {
searchCondition.put("userName", user.getUserName());
}else {
searchCondition.put("userName", null);
}
if(StringUtils.isNotBlank(user.getUserAddr())) {
searchCondition.put("userAddr", user.getUserAddr());
}else {
searchCondition.put("userAddr", null);
}
if (-1 != user.getStatus()) {
searchCondition.put("status", user.getStatus());
}else {
searchCondition.put("status", null);
}
if (-1 != user.getRoleId()) {
searchCondition.put("roleId", user.getRoleId());
}else {
searchCondition.put("roleId", null);
}
if (StringUtils.isNotBlank(user.getDate())) {
String[] dates = user.getDate().split(" - ");
searchCondition.put("startDate", dates[0]);
searchCondition.put("endDate", dates[1]);
}else {
searchCondition.put("startDate", null);
searchCondition.put("endDate", null);
}
List list = userMapper.getUserList(new RowBounds(user.getOffset(), user.getPageSize()), searchCondition);
int count = userMapper.getUserListCount(new RowBounds(user.getOffset(), user.getPageSize()), searchCondition);
R r = new R(user.getDraw(), count, count, list);
return r;
}
@Override
public int insert(User user) {
//设置创建时间
user.setCreateDate(new Date());
return userMapper.insert(user);
}
@Override
public int delete(Integer userId) {
return userMapper.delete(userId);
}
@Override
public User getById(Integer userId) {
return userMapper.getById(userId);
}
@Override
public int updateById(User user) {
return userMapper.updateById(user);
}
}
8、controller 层
package com.datatables.demo.controller;
import com.datatables.demo.bean.User;
import com.datatables.demo.common.res.R;
import com.datatables.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/list")
public R list(User user) {
R r = userService.getPageUserList(user);
return r;
}
@PostMapping("/add")
public String add(User user) {
try {
userService.insert(user);
return "添加成功";
}catch (Exception e){
e.printStackTrace();
return "添加失败";
}
}
@GetMapping("/delete")
public String delete(Integer userId) {
try {
userService.delete(userId);
return "删除成功";
}catch (Exception e){
e.printStackTrace();
return "删除失败";
}
}
@GetMapping("/get")
public User getById(Integer userId) {
return userService.getById(userId);
}
@PostMapping("/update")
public String update(User user) {
try {
userService.updateById(user);
return "修改成功";
}catch (Exception e){
e.printStackTrace();
return "修改失败";
}
}
}
9、springboot启动类
package com.datatables.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DatatablesDemoApplication {
public static void main(String[] args) {
SpringApplication.run(DatatablesDemoApplication.class, args);
}
}
10、前端 html 页面
Title
序号
ID
用户名
用户地址
创建时间
状态
角色名
操作
码云地址:https://gitee.com/wsjzzcbq/datatables-demo