Use Springboot + Thymeleaf+Mybatis to realize the addition, deletion, modification and paging query of Mysql database

Article catalogue

I Create a spring project using IDEA

II Establish project structure

III Create database

IV Import pom dependencies

V Writing pojo entity classes

Vi Write dao layer

VII Write service layer

VIII Write controller layer

IX Write usermapper XML Mapping File

X Write yml configuration information

Xi Write front page

XII test

I Create a spring project using IDEA

 

II Establish project structure

dao layer is used to write the interface of sql method, method interface and method implementation class of service layer, and control layer. pojo entity class, where the query package stores entity classes related to paging. The User class stores the entity class of the data table.

Create usermapper.com in the resources directory XML to write the specific code of sql method. Create edituser under templates Html is the data editing page, index Html is the home page, that is, the data display page. Create application YML write connection configuration information.

III Create database

---- we create a mybatis database and create a user table under the database, including ID, name and PWD attributes. I use Navicat visual Mysql tool to create it directly.

 

---- it can also be created in cmd through sql statement. After creating the database mybatis, enter the user code. In idea, you can use database to test the connectivity with the database.

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(55)  NOT NULL,
  `pwd` varchar(55)  NOT NULL,
  PRIMARY KEY (`id`)
)

IV Import pom dependencies

---- if the dependency is popular, it means that there is no dependency locally. You need to go to MAVEN warehouse to download dependency and import dependency methods manually How to manually import dependencies in pom to solve the problem of Dependency not found_ A Yige's blog - CSDN blog

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>wuhobin</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--Thymeleaf -->
        <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>
        <!-- integration mybatis Required dependencies-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--     Database driven      -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--  Database connection pool      -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!--Import lombok Can only be used data annotation -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- Paging dependency -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

V Writing pojo entity classes

---- create a query package and write a UserQuery entity class under the package to store the related entity attributes of paging

package wuhobin.pojo.query;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data       //Use the data annotation to omit the set and get methods
@AllArgsConstructor
@NoArgsConstructor
public class UserQuery {
    private Integer pageNum = 1;   // Current page number
    private Integer pageSize  = 2;   //Quantity displayed per page
    private String name;    // Query by user
}

---- write a User entity class to store the field properties of the data table

package wuhobin.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data        //Use the data annotation to omit the get and set methods
@AllArgsConstructor        //Automatic construction of parametric construction method
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
    private String pwd;
    private String perm;
}

Vi Write dao layer

---- UserDao writes the method interface required for database operation. You need to add @ Mapper annotation before you can use it in usermapper XML to write sql statements for interface methods

package wuhobin.dao;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import wuhobin.pojo.User;
import wuhobin.pojo.query.UserQuery;
import java.util.List;

@Mapper  // Tell springboot that this is a mapepr class of mybatis
@Repository   // Put userdao under the management of spring Rongqi
public interface UserDao {
    // Query all users
    public List<User> listUser();

    // Query user by id
    public User queryUserById(Integer id);

    // Query users according to their user names and display them in pages
    public List<User> listUserByName(UserQuery userQuery);

    //Delete user by id
    public int deleteUserById(Integer id);

    // Modify user
    public int updateUser(User user);

    // New user
    public int addUser(User user);
}

VII Write service layer

---- write UserService method interface

package wuhobin.service;

import com.github.pagehelper.PageInfo;
import wuhobin.pojo.User;
import wuhobin.pojo.query.UserQuery;

import java.util.List;

public interface UserService {
    // Query all users
    public List<User> listUser();

    // Query users according to their user names and display them in pages
    public PageInfo<User> listUserByName(UserQuery userQuery);

    //Delete user by id
    public boolean deleteUserById(Integer id);

    // Query user by id
    public User queryUserById(Integer id);

    // Modify user
    public boolean updateUser(User user);

    // New user
    public boolean addUser(User user);

}

---- write the implementation class of UserServiceImpl method

package wuhobin.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wuhobin.dao.UserDao;
import wuhobin.pojo.User;
import wuhobin.pojo.query.UserQuery;

import java.util.List;

@Service   //  To be managed by spring Rongqi
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> listUser() {
        return userDao.listUser();
    }

    @Override
    public PageInfo<User> listUserByName(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());
        return new PageInfo<User>(userDao.listUserByName(userQuery));
    }

    @Override
    public boolean deleteUserById(Integer id) {
        int i = userDao.deleteUserById(id);
        if(i > 0){              //Judge whether the user is successfully deleted
            return true;
        }else {
            return false;
        }
    }

    @Override
    public User queryUserById(Integer id) {
        return userDao.queryUserById(id);
    }

    @Override
    public boolean updateUser(User user) {
        int i = userDao.updateUser(user);
        if(i > 0){          //Judge whether the user is successfully edited
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user) > 0 ? true : false ;       //Judge whether the user is successfully added
    }
}

VIII Write controller layer

package wuhobin.controller;

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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import wuhobin.pojo.User;
import wuhobin.pojo.query.UserQuery;
import wuhobin.service.UserService;

@Controller
public class    UserController {
    @Autowired      //Automatic injection
    private UserService userService;

    @GetMapping("/")    //Enter the home page, which displays the database data
    public String index(Model model, UserQuery userQuery){
        PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
        model.addAttribute("page",userPageInfo);
        return "index";
    }

    @PostMapping("/")
    public String listUserByName(Model model,UserQuery userQuery){
        PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
        model.addAttribute("page",userPageInfo);
        return "index";
    }

    @GetMapping("/delete/{id}")     //Delete the data according to the id, and display the deletion result feedback on the front end
    public String delete(@PathVariable("id") Integer id, RedirectAttributes attributes){
        boolean b = userService.deleteUserById(id);
        if(b){
            attributes.addFlashAttribute("message","User deleted successfully");
            return "redirect:/";
        }else {
            attributes.addFlashAttribute("message","Failed to delete user");
            return "redirect:/";
        }
    }


    @GetMapping("/edit/{id}")       //Enter the data editing interface editUser according to the id
   public String toEdit(@PathVariable Integer id,Model model){
        model.addAttribute("user",userService.queryUserById(id));
        return "editUser";
   }


   @PostMapping("/edit")        //Edit and modify the data information, and show whether the modification results are successfully fed back in the front end
   public String edit(User user,RedirectAttributes attributes){
       UserQuery userQuery = new UserQuery();
       Integer id = user.getId();
      userQuery.setName(user.getName());
       PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
        if(id != null){
            if(userPageInfo.getSize() == 0){
                boolean b = userService.updateUser(user);
                if(b){
                    attributes.addFlashAttribute("message"," Update user succeeded");
                    return "redirect:/";
                }else {
                    attributes.addFlashAttribute("message","Failed to update user");
                    return "redirect:/";
                }
            }else {
                attributes.addFlashAttribute("message","The user name already exists");
                return "redirect:/edit/"+user.getId();
            }
        }else {
            if(userPageInfo.getSize() == 0){
                boolean b = userService.addUser(user);
                if(b){
                    attributes.addFlashAttribute("message"," Successfully added user");
                    return "redirect:/";
                }else {
                    attributes.addFlashAttribute("message","Failed to add user");
                    return "redirect:/";
                }
            }else {
                attributes.addFlashAttribute("message","The user name already exists");
                return "redirect:/";
            }
        }
   }

}

IX Write usermapper XML Mapping File

---- write specific sql methods for the methods in the UserDao interface

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="wuhobin.dao.UserDao">
    <select id="listUser" resultType="wuhobin.pojo.User">
        select *
        from mybatis.user;
    </select>

    <select id="listUserByName" parameterType="wuhobin.pojo.query.UserQuery" resultType="wuhobin.pojo.User">
        select *
        from mybatis.user
        <where>
            <if test="name != null and name != ''">
                and `name` like concat('%',#{name},'%')
            </if>
        </where>
    </select>

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>

    <select id="queryUserById" parameterType="int" resultType="wuhobin.pojo.User">
        select * from mybatis.user where  id=#{id}
    </select>


    <update id="updateUser" parameterType="wuhobin.pojo.User">
        update mybatis.user
        set name = #{name},pwd = #{pwd}
        where id = #{id}
    </update>

    <insert id="addUser" parameterType="wuhobin.pojo.User">
        insert into mybatis.user(name, pwd) values (#{name},#{pwd})
    </insert>
</mapper>

X Write yml configuration information

server:
  port: 8080

# Database data source
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root    # Change to your own database name
    password: 123456    #Change to your own database password
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  type-aliases-package: wuhobin.pojo   #   alias
  mapper-locations: classpath:/mybatis/*.xml   #   xml file

logging:
  file:
    name: log/log.log
  level:
    root: info
    wuhobin: debug

Xi Write front page

--- put the front page under the templates package and attach the code below

        ----editUser.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Modify user</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
</head>
<body>
<div class="ui container">
    <form class="ui form" th:action="@{/edit}" method="post" th:object="${user}">
        <input type="hidden" th:value="*{id}" name="id">
        <div class="field">
            <label>user name</label>
            <input type="text" name="name" placeholder="enter one user name" required th:value="*{name}">
        </div>
        <div class="field">
            <label>password</label>
            <input type="text" name="pwd" placeholder="Please input a password" required th:value="*{pwd}">
        </div>
        <button class="ui button" type="submit">Submit</button>
    </form>

    <div class="ui success  message" th:unless="${#strings.isEmpty(message)}">
        <i class="close icon"></i>
        <div class="header">Tips:</div>
        <p th:text="${message}"></p>
    </div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
<script>
    $(".message .close").on('click',function () {
        $(this).closest(".message")
            .transition("fade");
    })
</script>
</body>
</html>

        ----index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>home page</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
</head>
<body>
<div class="ui container">
    <div class="ui attached segment">
        <form th:action="@{/}" method="post" style="display: inline-block !important;">
            <input type="text" name="name" placeholder="Enter user name to find">
            <input type="submit" value="search">
        </form>
        <a th:href="@{/update}" class="ui button mini teal" style="margin-left: 30px !important;">newly added</a>
    </div>
    <table class="ui celled attached table" style="margin-top: 40px !important;">
        <thead>
        <tr><th>id</th>
            <th>full name</th>
            <th>password</th>
            <th>operation</th>
        </tr></thead>
        <tbody>
        <tr th:each="user : ${page.list}">                  <!--Traversal array, traversal array variable named user,from page Get it inside list aggregate-->
            <td th:text="${user.id}">James</td>
            <td th:text="${user.name}">24</td>
            <td th:text="${user.pwd}">Engineer</td>
            <td>
                <a th:href="@{/edit/{id}(id=${user.id})}" class="ui button mini pink">edit</a>
                <a th:href="@{/delete/{id}(id=${user.id})}" class="ui button mini teal">delete</a>
            </td>
        </tr>
        </tbody>
    </table>
    <div class="ui attached segment" >
        <table class="m-mobile-wide" width="425px">
            <tbody>
            <tr align="center">
                <td>
                    <a th:href="@{/(pageNum=${page.pageNum}-1)}"  class="ui button basic mini" th:unless="${page.isFirstPage}">previous page</a>
                </td>
                <td>
                    The first
                    <h8 th:text="${page.pageNum}">2</h8>
                    page/common
                    <h8 th:text="${page.pages}">4</h8>
                    page
                    common
                    <h8 th:text="${page.total}">29</h8>
                    strip
                </td>
                <td>
                    <form name="pageForm" th:action="@{/}" method="get">
                        <div class="ui mini input ">
                            <input type="text" class="m-bg" name="pageNum" placeholder="Page number" style="width: 50px!important; height: 27.76px!important;" required>
                            <button type="submit" style="font-size: 11px!important;width: 30px!important; height: 0px!important; border: none;margin: 5px;padding: 0;" class="button mini">
                                Jump
                            </button>
                        </div>
                    </form>
                </td>
                <td> &nbsp;</td>
                <td  style="float: right">
                    <a th:href="@{/(pageNum=${page.pageNum}+1)}" class="ui button basic mini " style="float: right;" th:unless="${page.isLastPage}">next page</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>          <!--Paging code-->
    <div class="ui success  message" th:unless="${#strings.isEmpty(message)}">
        <i class="close icon"></i>
        <div class="header">Tips:</div>
        <p th:text="${message}"></p>
    </div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
<script>
    $(".message .close").on('click',function () {
        $(this).closest(".message")
            .transition("fade");
    })
</script>
</body>
</html>

XII test

---- enter in the browser locahost://8080 , the results are as follows

 

Keywords: Database MySQL Spring Boot

Added by bouton on Fri, 04 Feb 2022 09:56:32 +0200