首先需要导入相关依赖Mybatis-plus和thymeleaf相关依赖,因为我导入依赖之前出现过依赖之间版本不匹配导致启动报错,这里我把整个pom.xml文件复制过来内容如下。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>testdemoartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.5.RELEASEversion>
<relativePath/>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.18version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.21version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.30version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
导入依赖后先写Mybatis-plus配置类,首先新建一个package包可以叫做config,然后再config下面新建配置类MybatisConfig内容如下。
@Configuration
public class MybatisConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
return mybatisPlusInterceptor;
}
}
这样分页相关的类就可以使用了。
然后我们先创建实体类与数据库相对应,类名UserEntity代码如下。
@Data
@TableName(value = "t_user")
public class User {
/**
* 用户表主键Id
*/
@TableId
private String userId;
/**
* 用户姓名
*/
private String userName;
/**
* 用户年龄
*/
private String userAge;
/**
* 用户住址
*/
private String userAddr;
/**
* 用户性别
*/
private String userSex;
/**
* 用户电话号码
*/
private String userPhone;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserAddr() {
return userAddr;
}
public void setUserAddr(String userAddr) {
this.userAddr = userAddr;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
}
当然如果我们使用了lombok插件后就不需要写set和get方法了,然后mybatis-plus需要注意的是,实体类与数据库的主键需要用@TableId注解来绑定一下,否则可能会出现错误。然后实体类的表名用@TableName(value = “t_user”)指定好表名就可以了。接下来创建Mapper接口名叫UserMapper即可。代码如下。
@Mapper
public interface UserMapper extends BaseMapper<User> {
//根据id删除雨量信息
@Delete("delete from t_user where user_id=#{id}")
int deleteUserById(String id);
@Select("select * from t_user where user_id=#{id}")
User getUserById(String id);
@Select("select user_id,user_name,user_age,user_addr,user_sex,user_phone,create_time from t_user order by create_time desc ")
List<User> selectList();
}
我们的mapper类需要继承一下plus的接口,因为它里面也自带了一些方法不需要我们手写sql,具体使用网上百度即可,我这里列出了我自己使用的sql用注解标注然后拼sql的方式。因为我这里不涉及业务方面就是简单的增删改查和分页所以没有业务逻辑层service层,创建一个接口UserController,然后代码如下。
@Controller
@RequestMapping("api/v1/user")
public class UserController {
@Autowired
private UserMapper userMapper;
/**
* 删除用户接口
*
* @param id t_user表的主键id
* @return
*/
@RequestMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") String id) {
userMapper.deleteUserById(id);
return "redirect:/api/v1/user/list";
}
/**
* 根据id修改用户信息
*
* @param model
* @param id
* @return
*/
@GetMapping("/updatePage/{id}")
public String updatePage(Model model, @PathVariable String id) {
User users = userMapper.getUserById(id);
model.addAttribute("users", users);
//表示跳转到modifie,html界面
return "modifie";
}
/**
* 编辑用户信息
*
* @param user 用户实体
* @param request
* @return
*/
@PostMapping("/update")
public String updateUser(User user, HttpServletRequest request) {
System.out.println(user);
userMapper.updateById(user);
return "redirect:/api/v1/user/list";
}
/**
* 跳转到新增页面
*
* @return
*/
@GetMapping("/insert")
public String insertOne() {
return "add.html";
}
/**
* 保存用户信息
*
* @param user 用户实体
* @return
*/
@PostMapping("/add")
public String saveUser(User user) {
String userId = UUID.randomUUID().toString().replaceAll("-", "");
user.setUserId(userId);
System.out.println(userId);
userMapper.insert(user);
//表示重置index.html界面并且跳转到index.html界面
return "redirect:/api/v1/user/list";
}
/**
* @param model model视图对象
* @param pn 第几页
* @return
*/
@GetMapping("/list")
public String getList(Model model, @RequestParam(value = "pn", defaultValue = "1") Integer pn) {
//分页查询数据,每页显示5条,
Page<User> userPage = new Page<>(pn, 10);
//分页查询的结果
Page<User> page = userMapper.selectPage(userPage, null);
model.addAttribute("page", page);
return "login.html";
}
接下来我们需要画页面了因为用的是thymeleaf所以我们在resources下面创建templates文件夹创建html。我们一共用到了3个页面,首先是login.html内容如下。
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
head>
<style>
a{
color: #ffffff;
}
h1{
/*文字对齐*/
text-align: center;
}
style>
<body>
<div class="container">
<button class="btn btn-success pull-right"><a th:href="@{'/api/v1/user/insert'}">添加用户a>button>
<h1>用户管理系统h1>
<table class="table table-striped table-bordered table-hover text-center">
<thead>
<tr style="text-align:center">
<th style="text-align:center">姓名th>
<th style="text-align:center">年龄th>
<th style="text-align:center">住址th>
<th style="text-align:center">性别th>
<th style="text-align:center">电话号码th>
tr>
thead>
<tr th:each="user:${page.records}">
<td style="vertical-align: middle!important;" th:text="${user.userName}">td>
<td style="vertical-align: middle!important;" th:text="${user.userAge}">td>
<td style="vertical-align: middle!important;" th:text="${user.userAddr}">td>
<td style="vertical-align: middle!important;" th:text="${user.userSex}">td>
<td style="vertical-align: middle!important;" th:text="${user.userPhone}">td>
<td>
<a class="btn btn-primary" th:href="@{'/api/v1/user/updatePage/'+${user.userId}}">更改a>
<a class="btn btn-danger" th:href="@{'/api/v1/user/delete/'+${user.userId}}">删除a>
td>
tr>
table>
<div class="row">
<div class="col-md-6" >当前 [[${page.current}]]页,总[[${page.pages }]]
页,总[[ ${page.total }]] 条记录div>
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<th:block th:if="${page.current==1}">
<li class="active,disabled">
<a>首页a>li>
th:block>
<th:block th:if="${page.current>1}">
<li><a th:href="@{/list(pn=1)}">首页a>li>
th:block>
<li th:if="${page.hasPrevious()}">
<a th:href="@{/list(pn=${page.getCurrent()-1})}">
<span aria-hidden="true">«span>
a>
li>
<th:block th:if="${page.getCurrent()<=3}" th:each="i:${#numbers.sequence(1,5)}">
<th:block th:if="${page.getCurrent()==i}">
<li class="active" >
<a th:text="${i}">a>
li>
th:block>
<th:block th:if="${page.getCurrent()!=i}">
<li>
<a th:text="${i}" th:href="@{/api/v1/user/list(pn=${i})}">a>
li>
th:block>
th:block>
<th:block th:if="${page.getCurrent()>3 && page.getCurrent()+2<=page.getPages()}"
th:each="i:${#numbers.sequence(page.getCurrent()-2,page.getCurrent()+2)}">
<th:block th:if="${page.getCurrent()==i}">
<li class="active" >
<a th:text="${i}">a>
li>
th:block>
<th:block th:if="${page.getCurrent()!=i}">
<li>
<a th:text="${i}" th:href="@{/api/v1/user/list(pn=${i})}">a>
li>
th:block>
th:block>
<th:block th:if="${page.getCurrent()+2>page.getPages()}"
th:each="i:${#numbers.sequence(page.getPages()-4,page.getPages())}">
<th:block th:if="${page.getCurrent()==i}">
<li class="active,disabled" >
<a th:text="${i}">a>
li>
th:block>
<th:block th:if="${page.getCurrent()!=i}">
<li>
<a th:text="${i}" th:href="@{/api/v1/user/list(pn=${i})}">a>
li>
th:block>
th:block>
<li th:if="${page.hasNext()}">
<a th:href="@{/api/v1/user/list(pn=${page.current+1})}">
<span aria-hidden="true">»span>
a>li>
<th:block th:if="${page.current" >
<li > <a th:href="@{/api/v1/user/list(pn=${page.pages})}">末页a>li>
th:block>
<th:block th:if="${page.current==page.pages}">
<li class="active,disabled"> <a>末页a>li>
th:block>
ul>
nav>
div>
div>
div>
body>
html>
接下来是修改用户信息的页面modifie.html内容如下。
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改用户title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
head>
<body>
<div style="width:400px;height:100%;margin-left:450px;margin-top:100px;">
<form action="/api/v1/user/update" method="post">
<input name="_method" type="hidden" value="put">
<input type="hidden" th:value="${users.userId}" name="userId">
姓 名:<input class="form-control" type="text" th:value="${users.userName}" name="userName"><br>
年 龄:<input class="form-control" type="text" th:value="${users.userAge}" name="userAge"><br>
住 址:<input class="form-control" type="text" th:value="${users.userAddr}" name="userAddr"><br>
性 别:<input class="form-control" type="text" th:value="${users.userSex}" name="userSex"><br>
电话号码:<input class="form-control" type="text" th:value="${users.userPhone}" name="userPhone"><br>
<button class="btn btn-primary btn-lg btn-block" type="submit">保存button>
form>
div>
body>
html>
最后是添加的add.html页面内容如下。
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
head>
<body>
<div style="width:400px;height:100%;margin-left:450px;margin-top:100px;">
<form action="/api/v1/user/add" method="post">
姓 名:<input class="form-control" type="text" th:value="${userName}" name="userName"><br>
年 龄:<input class="form-control" type="text" th:value="${userAge}" name="userAge"><br>
住 址:<input class="form-control" type="text" th:value="${userAddr}" name="userAddr"><br>
性 别:<input class="form-control" type="text" th:value="${userSex}" name="userSex"><br>
电话号码:<input class="form-control" type="text" th:value="${userPhone}" name="userPhone"><br>
<button class="btn btn-primary btn-lg btn-block">保存button>
form>
div>
body>
html>
这里面也引用了bootstrap的样式结合thymeleaf一起实现。然后我们最后需要在application.yml里面配置一下相关属性。配置如下。
server:
port: 8080
spring:
application:
name: user
thymeleaf:
cache: false
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
接下来我们运行我们的启动类即可。最后页面展示的效果如下图。
页面不是特别美观如果有兴趣可以自己在样式上拓展一下,本人是个小白,也借鉴了别人博客的内容做参考,写这篇博客的目的就是想记录一下而已,希望能帮到大家。