SpringBoot+Mybatis-plus+thymeleaf列表的增删改查即分页展示

首先需要导入相关依赖Mybatis-plus和thymeleaf相关依赖,因为我导入依赖之前出现过依赖之间版本不匹配导致启动报错,这里我把整个pom.xml文件复制过来内容如下。

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>testdemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

       <!-- <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>-->

        <!--<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
            <scope>test</scope>
        </dependency>-->

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.5.1</version>
        </dependency>-->

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </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>
    <!-- 引入 Bootstrap -->
<!--
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
-->
    <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-striped:斑马线格式,table-bordered:带边框的表格,table-hover:鼠标悬停高亮的表格-->
<table class="table table-striped table-bordered table-hover text-center">
    <thead>
    <tr style="text-align:center">
        <!--        th标签定义html表格中的表头单元格-->
        <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标签定义html表格中的所有行-->
    <!--    遍历集合,如果被遍历的变量users为null或者不存在,则不会进行遍历,也不会报错-->
    <tr th:each="user:${page.records}">
        <!--        td标签定义html表格中的标准单元格-->
        <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标签用来定义超链接 href表示超链接-->
            <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">&laquo;</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">&raquo;</span>
                    </a></li>


                <!--点击末页会跳转到最后一页,并且最后一页禁用-->
                <th:block th:if="${page.current<page.pages}">
                    <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 href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">-->
    <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">
        <!-- rest风格中的更新是put请求,
        所以这块先使用post请求,然后隐藏起来改为put请求-->
        <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 href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">-->
    <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

接下来我们运行我们的启动类即可。最后页面展示的效果如下图。
在这里插入图片描述
页面不是特别美观如果有兴趣可以自己在样式上拓展一下,本人是个小白,也借鉴了别人博客的内容做参考,写这篇博客的目的就是想记录一下而已,希望能帮到大家。

  • 5
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值