Spring Boot 整合 Mybatis-Plus
1.Spring 整合 Mybatis-Plus
a.链接:https://www.cnblogs.com/vettel0329/p/11990721.html
2.后端搭建:
a.在数据库创建 tb_user 用户表
-- 用户表 CREATE TABLE `tb_user` ( `id` varchar(255) NOT NULL, `user_name` varchar(255) NOT NULL, `user_code` int(11) NOT NULL, PRIMARY KEY (`id`) );
b.创建SpringBoot工程,选择依赖 Web、Thymeleaf、Mysql Driver,并手动添加 Mybatis-Plus 的SpringBoot依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> ...... <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> ...... </dependencies>
c.编辑 application.yml 配置文件
# 服务端口 server: port: 8081 spring: # 服务名称 application: name: springboot-mybatis-plus # 数据源配置 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC username: root password: 123456 # thymeleaf热更新 thymeleaf: cache: false # mybatis-plus相关配置 mybatis-plus: # entity扫描 type-aliases-package: com.wode.springbootmybatisplus.entity global-config: db-config: # AUTO -> 数据库ID自增 # INPUT -> 用户输入ID # ID_WORKER -> 全局唯一ID(数字类型唯一ID) # UUID -> 全局唯一ID(UUID) id-type: UUID # 全局表前缀 table-prefix: tb_
d.创建 Mybatis-Plus 配置类
@Configuration @EnableTransactionManagement //开启事务 @MapperScan("com.wode.springbootmybatisplus.dao") //mapper扫描 public class MybatisPlusConfig { //分页插件 @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
e.创建entity实体类
@TableName public class User { @TableId private String id; private String userName; private int userCode; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserCode() { return userCode; } public void setUserCode(int userCode) { this.userCode = userCode; } @Override public String toString() { return "User(id[" + id + "], userName[" + userName + "], userCode[" + userCode + "])"; } }
f.创建Dao
public interface UserMapper extends BaseMapper<User> { }
g.创建Service
@Service public class UserService { @Resource private UserMapper userMapper; public boolean addUser(User user){ if(userMapper.insert(user) > 0){ return true; } return false; } public boolean updateUser(User user){ if(userMapper.updateById(user) > 0){ return true; } return false; } public User getUser(String id){ return userMapper.selectById(id); } public IPage<User> getUserList(int currentPage, int pageSize){ Page<User> page = new Page<>(currentPage, pageSize); QueryWrapper<User> queryWrapper = new QueryWrapper<>(); return userMapper.selectPage(page, queryWrapper); } public boolean deleteUser(String id){ if(userMapper.deleteById(id) > 0){ return true; } return false; } }
h.创建Controller
@RestController @RequestMapping("/user") public class UserController { @Resource private UserService userService; @PostMapping("/add") public String addUser(User user) { if(userService.addUser(user)){ return "Success"; } return "Failure"; } @PostMapping("/update") public String updateUser(User user) { if(userService.updateUser(user)){ return "Success"; } return "Failure"; } @RequestMapping("/get/{id}") public User getUser(@PathVariable("id") String id) { return userService.getUser(id); } @RequestMapping("/list") public IPage<User> getUserList(int currentPage, int pageSize){ return userService.getUserList(currentPage, pageSize); } @RequestMapping("/delete/{id}") public String deleteUser(@PathVariable("id") String id){ if(userService.deleteUser(id)){ return "Success"; } return "Failure"; } }
@Controller public class PageController { //默认页面 @RequestMapping("/") public String index() { return "home"; } //跳转到首页 @RequestMapping("/home") public String home() { return "home"; } //跳转到详情 @RequestMapping("/detail") public String detail() { return "detail"; } }
3.前端测试
a.在 resources/templates 下创建 home.html 和 detail.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> <link rel="stylesheet" href="css/common.css"/> </head> <body> <div> <h1>首页</h1> <div class="row"> <table id="list-table" border="1"> <tr> <th>ID</th> <th>账号</th> <th>编号</th> <th>操作</th> </tr> </table> </div> <div class="row"> <div class="col"> <button id="list-btn">用户列表</button> </div> <div class="col"> <button id="add-btn">添加用户</button> </div> </div> </div> </body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="js/home.js"></script> </html>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>保存</title> <link rel="stylesheet" href="css/common.css"/> </head> <body> <div> <h1>保存</h1> <div class="row"> <div class="col"> <label>用户名:</label><input id="username-input" type="text"/> </div> </div> <div class="row"> <div class="col"> <label>编号:</label><input id="usercode-input" type="text"/> </div> </div> <div class="row"> <div class="col"> <button id="save-btn">保存</button> </div> <div class="col"> <button id="close-btn">关闭</button> </div> </div> <input id="id" type="hidden" th:value="${#request.getParameter('id')}" /> </div> </body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="js/detail.js"></script> </html>
b.在 resources/static/css 下创建 common.css
.row{ margin:10px 0px; } .col{ display: inline-block; margin:0px 5px; }
c.在 resources/static/css 下创建 home.js 和 detail.js
$(function() { //获取用户列表 $("#list-btn").on("click", getUserListFunc); //用户详情 $(document).on("click", ".detail-btn",function(){ let id = $(this).attr('data-id'); location.href = "detail?id=" + id; }); //删除用户 $(document).on("click", ".delete-btn",function(){ let id = $(this).attr('data-id'); $.ajax({ url: "user/delete/" + id, success: function(data){ alert("删除成功!"); getUserListFunc(); }, error: function(e){ alert("系统错误!"); }, }) }); //添加用户 $("#add-btn").on("click",function(){ location.href = "detail"; }); }); //函数:获取用户列表 let getUserListFunc = function() { $.ajax({ url: "user/list", data: { currentPage: 1, pageSize: 100 }, success: function (data) { if (data) { $("#list-table").empty(); $("#list-table").html("<tr><th>ID</th><th>账号</th><th>编号</th><th>操作</th></tr>"); let userArray = data.records; for (let i in userArray) { let user = userArray[i]; let id = user.id; let userName = user.userName; let userCode = user.userCode let trTemplate = `<tr> <th>${id}</th> <th>${userName}</th> <th>${userCode}</th> <th> <button class="detail-btn" data-id="${id}">详情</button> <button class="delete-btn" data-id="${id}">删除</button> </th> </tr>`; $("#list-table").append(trTemplate); } } }, error: function (e) { console.log("系统错误!"); }, }) }
$(function() { //加载 let id = $("#id").val(); if(id){ $.ajax({ url: "user/get/" + id, success: function(data){ if(data){ let userName = data.userName; let userCode = data.userCode; $("#username-input").val(userName); $("#usercode-input").val(userCode); }else{ alert("系统错误!"); } }, error: function(e){ alert("系统错误!"); }, }) } //获取用户列表 $("#save-btn").on("click",function(){ let userName = $("#username-input").val(); if(! userName){ alert("用户名不能为空"); return; } let userCode = $("#usercode-input").val(); if(! userCode){ alert("编号不能为空"); return; } let user; let url; //修改 if(id){ url = "user/update"; user = { userName: userName, userCode: userCode, id: id }; //添加 }else{ url = "user/add"; user = { userName: userName, userCode: userCode }; } $.ajax({ url: url, type: "POST", data: user, success: function(data){ alert("保存成功!"); }, error: function(e){ alert("系统错误!"); }, }) }); //添加用户 $("#close-btn").on("click",function(){ location.href = "home"; }); });
d.访问 http://localhost:8080 进行测试