SpringBoot+Thymeleaf+mybatis+mysql简单入门增删查改案例

1.先决条件

JDK1.8、JPA相关知识、Mysql相关知识、Thymeleaf相关知识、SpringBoot构建项目,不了解的朋友可以看一下我前面的博
文。
thymeleaf入门

2.数据准备

  1. 创建数据库和表
create database thymeleaf;
use thymeleaf;
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30),
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
  1. 添加15条数据方便测试
INSERT INTO user VALUES (1,'name1');
INSERT INTO user VALUES (2,'name2');
INSERT INTO user VALUES (3,'name3');
INSERT INTO user VALUES (4,'name4');
INSERT INTO user VALUES (5,'name5');
INSERT INTO user VALUES (6,'name6');
INSERT INTO user VALUES (7,'name7');
INSERT INTO user VALUES (8,'name8');
INSERT INTO user VALUES (9,'name9');
INSERT INTO user VALUES (10,'name10');
INSERT INTO user VALUES (11,'name11');
INSERT INTO user VALUES (12,'name12');
INSERT INTO user VALUES (13,'name13');
INSERT INTO user VALUES (14,'name14');
INSERT INTO user VALUES (15,'name15');

3. 新建项目

模板选上web,模板引擎选择Thymeleaf
SpringBoot+Thymeleaf+mybatis+mysql简单入门增删查改案例

3.1 修改pom.xml文件

添加mybatis、mysql、分页工具pageHelper 的 依赖,最后依赖的配置如下:

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- servlet依赖. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>

        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- tomcat的支持.-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>

        </dependency>
        <!-- 添加mybatis的依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!-- 添加mysql的依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version><!--我装的是8.0.15,根据个人选择相应版本-->
        </dependency>
        <!-- pageHelper  用于分页 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>
    </dependencies>

3.2 修改application.properties文件

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
#上下文,可以不需要,如果加上则要在浏览器url加上/thymeleaf
#server.servlet.context-path=/thymeleaf

#数据库配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/thymeleaf?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=666666
#由于我用得是Mysql8.0 所以驱动类是 com.mysql.cj.jdbc.Driver如果是其他版本请改成com.mysql.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3.3 添加实体类

新建一个pojo包,新建一个实体类User

package com.eknaij.springbootthymeleaf.pojo;

public class User {
    Integer id;
    String name;

    public Integer getId() {        return id;    }
    public void setId(Integer id) {        this.id = id;    }
    public String getName() {        return name;
    }
    public void setName(String name) {        this.name = name;    }}

3.4 添加Mapper

新建一个mapper包,用于存放mapper接口文件
新建一个UserMapper接口

package com.eknaij.springbootthymeleaf.mapper;

import com.eknaij.springbootthymeleaf.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("select * from user ")
    List<User> findAll();

    @Insert(" insert into user  (name) values (#{name}) ")
    public int save(User user);

    @Delete(" delete from user where id= #{id} ")
    public void delete(int id);

    @Select("select * from user where id= #{id} ")
    public User get(int id);

    @Update("update user set name=#{name} where id=#{id} ")
    public int update(User user);
}


3.5 添加config包

添加config包,用于存放分页相关的配置类
新建用于分页配置的PageHelperConfig类

package com.eknaij.springbootthymeleaf.config;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class PageHelperConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}


3.6 新建controller

新建一个controller包,存放相关controller类
新建一个UserController

package com.eknaij.springbootthymeleaf.controller;

import com.eknaij.springbootthymeleaf.mapper.UserMapper;
import com.eknaij.springbootthymeleaf.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserMapper userMapper;

    //添加
    @RequestMapping("/addUser")
    public String listUser(User user) throws Exception {
        userMapper.save(user);
        return "redirect:listUser";
    }
    //删除
    @RequestMapping("/deleteUser")
    public String deleteUser(User user) throws Exception {
        userMapper.delete(user.getId());
        return "redirect:listUser";
    }
    //修改
    @RequestMapping("/updateUser")
    public String updateUser(User user) throws Exception {
        userMapper.update(user);
        return "redirect:listUser";
    }
    //查找(用于修改)
    @RequestMapping("/findUser")
    public String findUser(int id, Model model) throws Exception {
        User user= userMapper.get(id);
        model.addAttribute("user", user);
        return "edituser";
    }
    //遍历
    @RequestMapping("/listUser")
    public String listUser(Model model, @RequestParam(value = "start", defaultValue = "0") int start,
                           @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start,size,"id asc");
        List<User> userList=userMapper.findAll();
        PageInfo<User> page = new PageInfo<>(userList);
        model.addAttribute("pages", page);
        return "listuser";
    }
}


3.7 html页面

涉及到一些Thymeleaf的标签,如果不了解可以查看我的上一篇文章:Thymeleaf介绍以及常用标签

  1. 在resources/templates目录下新建一个layout.html页面(所有页面都建立在这个文件夹里),用于设置布局
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<header th:fragment="header">
    布局的head
</header>
<div th:replace="::content">
    这是正文
</div>
<footer th:fragment="footer">
   布局的foot
</footer>
</body>
</html>

这个布局只是简单的上中下三部分,在此只是简单示范一下thylemeaf的布局使用方法,不做具体样式。本页面相当于模板,在页面布局一致的情况下,只要修改content就好了。这个页面关键的地方在于:

<div th:include="::content">

  1. 新建一个listuser.html用于显示所有的User
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"  th:replace="layout">
<head>
    <meta  http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <title>遍历User</title>
</head>
<body>
<div  th:fragment="content" style="width:500px;margin:20px auto;text-align: center" >
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>编辑</td>
            <td>删除</td>
        </tr>
        <tr th:each="c:${pages.list}">
            <td th:text="${c.id}">1</td>
            <td th:text="${c.name}">name</td>
            <td><a th:href="@{/findUser(id=${c.id})}">编辑</a></td>
            <td><a th:href="@{/deleteUser(id=${c.id})}">删除</a></td>
        </tr>
    </table>
    <br/>
    <div>
        <a th:href="@{/listUser(start=0)}">[首  页]</a>
        <a th:href="@{/listUser(start=${pages.pageNum-1})}">[上一页]</a>
        <a th:href="@{/listUser(start=${pages.pageNum+1})}">[下一页]</a>
        <a th:href="@{/listUser(start=${pages.pages})}">[末  页]</a>
    </div>
    <br/>
    <form action="addUser" method="post">

        name: <input name="name"/> <br/>
        <button type="submit">添加</button>

    </form>
</div>
</body>
</html>

注意第二行的th:replace="layout",还有主体DIV的th:fragment="content"

  1. 新建一个edituser.html用于修改User
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>修改User</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div style="margin:0px auto; width:500px">

    <form action="updateUser" method="post">
        name: <input name="name" th:value="${user.name}"/> <br/>
        <input name="id" type="hidden" th:value="${user.id}"/>
        <button type="submit">提交</button>
    </form>
</div>
</body>
</html>

3.8 项目结构

SpringBoot+Thymeleaf+mybatis+mysql简单入门增删查改案例
文中未提及的类和hello.html可忽略,之前练习thymeleaf时留下的,就不删除了。

4. 运行测试

运行结果如下:

SpringBoot+Thymeleaf+mybatis+mysql简单入门增删查改案例

head和foot是我们布局文件中的内容(真丑= =),中间的表格才是我们的主体。

5. 总结

用thymeleaf模板引擎和使用JSP开发web项目大同小异,关键是要注意thymeleaf的一些属性与JSP有所差异,两个布局方法也有所不同,对于前后端分离来说,用thymeleaf来开发更方便。

本文源码已上传github.需要的话请自行下载:源码下载地址