Springboot+Mybatis+jpa+thymeleaf realizes adding, deleting, modifying and checking

project structure

insert image description here

pom file

Configuration related dependencies:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!--jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

Application configuration file

Here you need to configure according to the database information on your computer:
spring.datasource.url=jdbc:mysql://localhost/database name?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=username
spring.datasource .password=Password

#连接数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/changgou?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#jpa 相关配置
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
#thymelea模板配置
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html

Entity class

The class name must be the same as the database table name, and the fields in the class correspond to the fields in the table

package com.li.pojo;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

controller layer implementation class

package com.li.controller;

import com.li.pojo.User;
import com.li.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

        @Autowired
        private UserService userService;

        // 查询所有
        @GetMapping("/list")
        public String findUsers(Model model){
            List<User> users = userService.findUsers();
            model.addAttribute("users", users);
            return "index";
        }

        // 根据id查询
        @GetMapping("/edit")
        public String findUserById(Integer id, Model model){
            User user = userService.findUserById(id);
            model.addAttribute("user",user);
            return "update";
        }

        @RequestMapping("/show")
        public String show(){
            return "add";
        }

        // 添加
        @PostMapping(value = "/add")
        public String saveUser(User user){
            userService.addUser(user);
            return "redirect:/user/list";
        }

        // 更新
        @RequestMapping("/update")
        public String updateUser(User user){
            userService.updateUser(user);
            return "redirect:/user/list";
        }

        // 根据id删除
        @RequestMapping("/delete")
        public String deleteUserById(Integer id){
            userService.deleteUserById(id);
            return "redirect:/user/list";
        }

    }

service layer interface

package com.li.service;

import com.li.pojo.User;

import java.util.List;

public interface UserService {

    List<User> findUsers();

    User findUserById(Integer id);

    void addUser(User user);

    void updateUser(User user);

    void deleteUserById(Integer id);
}

service layer implementation class

package com.li.service.impl;

import com.li.dao.UserDao;
import com.li.pojo.User;
import com.li.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findUsers() {
        List<User> users = userDao.findAll();
        return users;
    }

    @Override
    public User findUserById(Integer id) {
        Optional<User> optional = userDao.findById(id);
        User user = optional.get();
        return user;
    }

    @Override
    public void addUser(User user) {
        userDao.save(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.save(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userDao.deleteById(id);
    }
}

dao layer interface

package com.li.dao;

import com.li.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User,Integer> {


}

startup class

package com.li;

import org.springframework.boot.SpringApplication;

@SpringBootApplication
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}

index.htmlHomepage

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a th:href="@{/user/show}">添加</a>
<div>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>USERNAME</th>
            <th>PASSWORD</th>
            <th></th>
        </tr>
        <!-- 通过th命令使用一些操作 -->
        <!-- 通过${} 使用变量 -->
        <tr  th:each="user:${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.username}"></td>
            <td th:text="${user.password}"></td>
            <td>
                <a th:href="@{/user/edit(id=${user.id})}">修改</a>
                <a th:href="@{/user/delete(id=${user.id})}">删除</a>
            </td>
        </tr>
    </table>
</div>
</body>
</html>

add.html add page

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/user/add" method="post" >
        <input type="hidden" name="id">
        username:<input type="text" name="username">
        password:<input type="password" name="password">
        <a href="/user/list">返回</a>
        <input type="submit" value="提交">
    </form>
</body>
</html>

update.htmlupdate page

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/user/update" th:object="${user}" method="post">
    <input type="hidden" name="id" th:id="*{id}" th:value="*{id}">
    用户名:<input type="text" id="username" name="username" th:value="*{username}">
    密  码:<input type="password" id="password" name="password" th:value="*{password}">
    <a href="/user/list">返回</a>
    <input type="submit" value="提交">
</form>
</body>
</html>

Create user table

CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

Add table data

INSERT INTO USER (username, PASSWORD) VALUES ('123','123');

Home display

insert image description here

Add to

Add a user name of 111 and a password of 123456
insert image description here
and return to the home page after adding:
insert image description here

Revise

Modify the password with id 1 to 123456:
insert image description here
Return to the home page after modification:
insert image description here

delete

Delete user with id 5:
insert image description here

Summarize

Build a maven project through springboot, combine Mybatis and jpa to quickly realize simple addition, deletion, modification and query, and use thymeleaf template technology to realize the display of the front-end page.

Guess you like

Origin blog.csdn.net/qq_41833935/article/details/105473811