我是靠谱客的博主 落后诺言,最近开发中收集的这篇文章主要介绍SpringBoot+Mybatis+Thymeleaf实现对数据库的增删改查,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

前沿:近来开始学习SpringBoot,实现对数据的基本操作。

本文使用Mybatis的注解版,Thymeleaf 模板用的及其简陋,仅提供简单的展示

1、引入依赖、POM文件如下:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mybatis-03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-03</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

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

</project>

 

2、创建配置文件,此处使用yml文件,文件内容如下:

spring:
  datasource:
    username: root
    password: li123
    url: jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

与数据库的连接

 

3、创建数据表(省略)

 

4、编写实体类:

package com.example.mybatis03.bean;

public class Department {
    public Integer getId() {
        return id;
    }

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

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", departmentName='" + departmentName + ''' +
                '}';
    }

    private Integer id;
    private String departmentName;

}

5、创建Mapper,注意@Mapper注解,此处使用注解版,只需在方法上写入SQL语句即可

package com.example.mybatis03.mapper;

import com.example.mybatis03.bean.Department;
import org.apache.ibatis.annotations.*;

import java.util.Collection;
import java.util.List;

@Mapper
public interface DepartmentMapper {

    @Select("select * from department")
    List<Department> findAll();

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public  int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);

}

6、Controller类的实现

(1)首先是查找操作,方法如下:

 @ResponseBody
    @RequestMapping("lists")
    public List<Department> findAll(){
        List<Department> list = departmentMapper.findAll();
        return list;
    }

在地址栏的输入和输出如下:

(2)在不和前端交互的情况下,插入方法如下:

    @ResponseBody
    @GetMapping("/dept")
    public Department insertDept(Department department, Model model) {
        departmentMapper.insertDept(department);

        return department;
    }

在网址栏输入的输入和输出如下:

数据库内容如下:

(3)修改操作,方法如下:

@ResponseBody
    @RequestMapping("update/{id}")
    public Department update(@PathVariable("id") Integer id,Department department) {
        departmentMapper.updateDept(department);
        return department;
    }

 

地址栏的输入以及结果如下:

数据库内容如下:

(4)删除操作,方法如下:

  @ResponseBody
    @RequestMapping("del/{id}")
    public String delete(@PathVariable("id") Integer id){
        departmentMapper.deleteDeptById(id);
        return "success";
    }

地址栏输入与结果如下:

7、整合Thymeleaf ,实现对数据的显示

Controller如下:

package com.example.mybatis03.controller;

import com.example.mybatis03.bean.Department;
import com.example.mybatis03.mapper.DepartmentMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("depts")
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;


    /*
        页面跳转不需要@ResponseBody注解
     */
    //显示所有信息
    @RequestMapping("list")
    public String findAll(Model model) {
        List<Department> list = departmentMapper.findAll();
//        JSONPObject jsonpObject = new JSONPObject("data", list);
        model.addAttribute("depts", list);
        return "showdept";
    }


    //单个查询
    @ResponseBody
    @RequestMapping("/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    //新增和添加操作

    @RequestMapping("/edit")
    public String editDept(ModelMap map, @RequestParam(defaultValue = "0") Integer id) {
        if (id > 0) {
            map.addAttribute("isAdd", false);
            map.addAttribute("dept", departmentMapper.getDeptById(id));
        } else {
            map.addAttribute("isAdd", true);
            map.addAttribute("dept", new Department());
        }
        return "update";
    }


    @ResponseBody
    @RequestMapping("/save")
    public String save(@ModelAttribute Department department) {
        if (department == null) {
            return "fail";
        }
        if (department.getId() != null && department.getId() > 0) {
            departmentMapper.updateDept(department);
        } else {
            departmentMapper.insertDept(department);
        }
        return "success";
    }


    //删除操作
    @GetMapping("/delete/{id}")
    public String deleteDept(@PathVariable("id") Integer id, Model model) {
        departmentMapper.deleteDeptById(id);
        List<Department> list = departmentMapper.findAll();
        model.addAttribute("depts", list);
        return "showdept";
    }

}

前端页面如下:

showdept.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="table-responsive">
    <h2><a class="btn btn-sm btn-success" href="dept" th:href="@{/depts/edit}">员工添加</a></h2>
    <table class="table table-striped table-sm">
        <thead>
        <tr>
            <th>#</th>
            <th>departmentName</th>
        </tr>
        </thead>
        <tbody>

        <tr th:each="dept:${depts}">
            <td th:text="${dept.id}"></td>
            <td th:text="${dept.departmentName}"></td>
            <td>
                <a class="btn btn-sm btn-primary" th:href="@{/depts/edit(id=${dept.id})}">编辑</a>
                <!--<button class="btn btn-sm btn-danger" >删除</button>-->
                <a th:href="@{/depts/delete/{id}(id=${dept.id})}">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

</body>
</html>

update.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/depts/save}" method="post">

    <div th:if="${isAdd} == false">
        <label>id</label>
        <input type="text" name="id" readonly="readonly" th:field="${dept.id}" />
    </div>
    <div>
        <label>departmentName</label>
        <input type="text" name="departmentName" th:field="${dept.departmentName}" />
    </div>

    <div>
        <input type="submit" value="提交" />
    </div>
</form>
</body>
</html>

最后

以上就是落后诺言为你收集整理的SpringBoot+Mybatis+Thymeleaf实现对数据库的增删改查的全部内容,希望文章能够帮你解决SpringBoot+Mybatis+Thymeleaf实现对数据库的增删改查所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部