SpringBoot+Mybatis-Plus realizes addition, deletion, modification and query (with video explanation)

Table of contents

1. Introduction

Video explanation

2. Preparatory work

(1) Create a springboot project and create a database

3. Project configuration

(1) Pom.xl imports related dependencies 

1. Import dependencies

(2) Configure the connection database in the yml file

2. Configure the yml file 

4. Code writing

database display

Project showing in advance! ! !

(3) MySQL table is bound to spring boot (entity layer)

3.1 Create entity package

 3.2 Write the User class

(4) springboot is bound to mybatis-plus (data layer)

4.1 Create mapper package

4.2 Write UserMapper interface

(5) Process the data layer into logical business (service service layer)

5.1 Create a service package 

5.2 Write and obtain the built-in addition, deletion, modification and query method interface IUserService

5.3 Write your own defined UserService

5.4 Write service layer synthesis logic business UserServiceImpl

5.5 Story Interpretation Service Layer Interfaces and Classes

(6) Call the emperor of the service layer

 6.1 Create a controller package

6.2 Write the UserController class that calls the business layer

5. Front-end request test


1. Introduction

This article integrates mybatis-plus through springboot to realize the addition, deletion, modification and query of the database at the back end and respond to the url of the front end, so that the front end can obtain data. The mybatis-plus technology simplifies the cumbersome code operations. It has built-in statements for adding, deleting, modifying and checking, and can directly call to realize adding, deleting, modifying and checking the database. It can also prevent SQL injection to a certain extent. The disadvantage is that it is not flexible enough, but you can also create code yourself to make up for this flexible problem.

Video explanation

Springboot integrates mybatis-plus additions, deletions, changes, and queries to get started quickly_哔哩哔哩_bilibili 

2. Preparatory work

(1) Create a springboot project and create a database

1. Introduction and creation method of spring boot project: Quick creation method of SpringBoot project (including the operation of the first program)

2. Detailed steps to create a MySQL database and create a new table:

 Detailed steps for creating a MySQL database and creating a table (navicat)

3. Project configuration

(1) Pom.xl imports related dependencies 

There are several necessary dependencies

1. Web dependency, this has been added when it was created, so there is no need to import it (check it)

2. Lombok dependency, this has been added when it was created, so there is no need to import it (check it)

3. The dependency of mybatis-plus (source baomidou)

4. mysql dependency

5.druid dependency (source Alibaba Druid)

6. swagger2 dependency (with this, the annotation @ApiModelProperty can be used)

1. Import dependencies

Import related dependencies in the pom.xml file. If the dependency is not added successfully, it is necessary to check your own maven configuration problem

maven solution:

Detailed steps of adding maven environment to springboot - Programmer Sought

The solution to spring-boot-maven-plugin reporting red

       <!--新加入的依赖1-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.3</version>
		</dependency>
		<!--新加入的依赖2-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.33</version>
		</dependency>
		<!--新加入的依赖3-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.2.16</version>
		</dependency>
		<!--新加入的依赖4  @ApiModelProperty这个才能用-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.7.0</version>
		</dependency>

 Right now:

(2) Configure the connection database in the yml file

2. Configure the yml file 

Change the suffix of the application configuration file to yml, so that it looks more clear, and then write the configuration of connecting to the database in it to establish an association with the database. The specific port number is 8080 by default, but I changed it to port 80. 

Lines 2, 7, 8, and 9 here must be changed to your own  

server:
  port: 80
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dndata?serverTimezone=GMT%2b8
    username: root
    password: 123456

4. Code writing

database display

Project showing in advance! ! !

(3) MySQL table is bound to spring boot (entity layer)

Why create this class?

It can be understood that this step is to bind the database fields and the back-end code 

3.1 Create entity package

Create a new entity package under the project , and then create a new class. The name of the class is User

Naming source: The class name is the same as the table name in the database, but the first letter should be capitalized, and an attribute class corresponds to a database table.

 3.2 Write the User class

The attributes in this entity class should correspond to the fields in the database  

It is very simple to write by looking at the comments. The comments at the bottom also explain the role of each comment 

User class

package com.example.mybatis.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/*
* 1.使用@Data注解
* 2.使用注解@TableName(value = "user") -----user这个是对应数据库的表名
* 3.编写和数据库字段对应的属性
* 4.加上文档注解@ApiModelProperty("用户的id")---里面的文字是相当于给自己看的备注
* 5.使用@TableId(value = "id", type = IdType.AUTO) //作用是标明当前属性主键,并且type = IdType.AUTO这个代表id自增
* */
@Data  //1
@TableName(value = "user")    //2
public class User {

    @ApiModelProperty("用户的id")  //4
    @TableId(value = "id", type = IdType.AUTO) //5
    private Integer id;  //3

    @ApiModelProperty("用户名")  //4
    private String username;  //3

    @ApiModelProperty("密码")  //4
    private String password;   //3
}

/*
* 注解的解释
* @Data:注解是这个来源于lombok,内置了set、get、ToString等属性类里面我们需要写的东西,就不用我们写了

* @TableName:注解是 MyBatis-Plus 框架中的一个注解,用于标识实体类与数据库表之间的映射关系。
* 它的作用是告诉 MyBatis-Plus 框架这个实体类对应哪个数据库表。

* @ApiModelProperty:注解是 Swagger 框架中的一个注解,
* 用于给实体类的属性(字段)添加额外的文档说明,以便在生成 API 文档时提供更详细的描述和信息。
* Swagger是一个用于生成和展示 API 文档的工具,可以帮助开发人员更好地理解和使用 API。
*
* @TableId 注解用于标识表的主键字段,帮助 MyBatis-Plus 框架了解哪个属性在数据库中扮演主键的角色,
* 以及如何生成主键值。这对于数据库操作和映射非常重要。
* */

(4) springboot is bound to mybatis-plus (data layer)

Why create this interface?

Because in order to bind the attribute class obtained by springboot to mybatis-plus, and then bind this interface to other layers.

4.1 Create mapper package

Create a mapper package under the project

4.2 Write UserMapper interface

Create an interface UserMapper , the naming source is the attribute class name + mapper, and the camel case is named

At this point, you can use the most original addition, deletion, modification and query built into mybatis-plus, but it is not flexible enough, and you can only do the simplest addition, deletion, modification and query.

UserMapper class

package com.example.mybatis.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
/*
* 1.使用@Mapper注解 ,代表这个接口被mybatis接管
* 2.继承BaseMapper<属性类名>
* */
@Mapper
public interface UserMapper extends BaseMapper<User> {
}


/*
* @Mapper:注解是 MyBatis 框架中的一个重要标识,
* 它定义了 Mapper 接口,用于与数据库交互。使用这个注解可以简化数据库操作代码,并提供一些优势,
* 如自动生成 SQL、类型安全性等。
* */

(5) Process the data layer into logical business (service service layer)

Why this layer?

Answer: This layer is called the service layer, also called the business layer. Because the above data is completely bound, it can be added, deleted, modified, and checked, but it is only the most primitive, and there are few encapsulation methods, and there are no more complicated pagination query methods, so it should be used at this layer Better methods and various logics packaged by others can be written here 

5.1 Create a service package 

5.2 Write and obtain the built-in addition, deletion, modification and query method interface IUserService

MP official

Why write this interface?

Inheriting the MP (mybatis-plus) packaged interface, all the methods of adding, deleting, modifying and checking that we need are written for us here. This interface is written to call the adding, deleting, modifying and checking in this interface for the later control layer method.

Why can’t you see the method of adding, deleting, modifying and checking?

Because it is encapsulated into this IService interface by MP

Create this IUserService interface under the service package

IUserService interface

package com.example.mybatis.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatis.entity.User;


//1.继承IService这个接口,<实体类名>
public interface IUserService extends IService<User> {
}

/*
IService接口里面有mybatis-plus封装好我们经常会用到的增删改查的一些方法
里面本质上还调用了上数据层mapper,是对mapper的封装优化
*/
5.3 Write your own defined UserService

 Create this UserService class under the service package

MP official + custom logic + call the data layer by yourself --- our own

5.2 Isn't there already a method for adding, deleting, modifying and checking, why write this?

Answer: The interface in 5.2 directly uses the built-in CRUD method of MP, which can be used normally, but I want to optimize the built-in CRUD, such as data encryption, data verification and other logical processing.

And I want to nest or upgrade and customize these built-in additions, deletions, changes, and queries according to my own needs?

All in all, the bottom layer of this class is the implementation class of the 5.2 interface, that is to say, this class contains the 5.2 interface . You can also customize methods and calls to the mapper data layer , which are more abundant than the methods of the 5.2 interface , and are used to add custom processing to the cumbersome logical data layer

package com.example.mybatis.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatis.entity.User;
import com.example.mybatis.mapper.UserMapper;
import org.springframework.stereotype.Service;

/*
* 1.使用@Service注解,要不然咱自己定义的类,谁知道他是服务层
* 2.继承ServiceImpl,这个是MP内置增删改查接口的一个实现,牛逼的是还能自定义直接调取数据层的数据
* 3.定义需要的方法,根据自己的需要定义,定义MP内置里面没有的
* */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    //下面这个方法是对数据库操作时候多加了一层封装,用不到去掉也没有影响。
    // 、作用可以定义密码加密、数据校验、关联数据处理、日志记录、通知或触发事件等
    public boolean saveUser(User user){
           return saveOrUpdate(user);
    }
}
5.4 Write service layer synthesis logic business UserServiceImpl

 Create this UserServiceImpl class under the service package 

1. Why write this implementation class?

Because the methods of 5.2 and 5.3 are used here to form logical services, such as login, verification, permissions, etc.

2. Why not use 5.3 directly, isn't it possible to define logical methods in that? 

5.3 The custom class is mainly used to deal with some low-level methods for data, password encryption, and verification of these low-level methods. And this class defines the business that is grouped by the small methods of 5.3, such as login, permission verification, etc.

All in all, here is the shaping of the business , call 5.3 (main) + 5.2 (secondary) + some logic to form the business

package com.example.mybatis.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatis.entity.User;
import com.example.mybatis.mapper.UserMapper;
import com.example.mybatis.service.IUserService;
import org.springframework.stereotype.Service;
/*
* 1.@Service--------使用@Service注解,让人知道这个是服务层
* 2.extends ServiceImpl<UserMapper, User> ---继承和UserService类里面继承的方法一样,
* 但是这里面还偷偷藏了UserService自定义的方法
* 3.implements IUserService---实现接口
* */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    //登录业务
    //登录校验业务
    //创建用户检查业务等等
}

5.5 Story Interpretation Service Layer Interfaces and Classes

What is the relationship between so many service layers, here is the interpretation 

These three are all service layers, depending on which one you need to choose to call

5.2 (The Landlord’s Silly Son) is a service interface that nests the commonly used CRUD built in MP

     Like the stupid son of the landlord's MP , he has nothing and only calls the methods written by his father, but there is a good father who has most of the commonly used CRUD, and the control layer can directly call him

5.3 (The servant's son) is a service class, nested with built-in CRUD + self-developed calling method

     Although this class has the same built-in methods as the landlord's silly son, it is more progressive and wants to become stronger, so you can customize and practice many methods: underlying password encryption, data verification, associated data processing, logging, notifications Or trigger events, and interact directly with the data layer.

Is this class great? Is it perfect? ​​The control layer will not call him, because these methods will be used by his father to form various logic services

5.4 (Servant) is a service class that implements 5.2 Landlord’s Silly Son, and also implements 5.3 Pro-Son. Unification

      Various businesses are realized here. Everything that can be written here is business, such as the login business composed of the 5.3 method, the authority verification business, and so on.

This is the daddy service class. That's good enough. But this cannot be called directly by the control layer, because this is not an interface. According to the design's dependency inversion principle, calling the interface can achieve the effect of decoupling. But these writing methods can’t be wasted. I can only inherit the interface of the silly son of the 5.2 landlord’s family and ask him to help me bring out all these logics. Injection through the controller constructor

(6) Call the emperor of the service layer

Why this layer?

Because it is called the control layer, it is the emperor. What do you want, tell me, I will let the service layer do the logic business.

Any data or logical business you want must go through my control layer, just ask me to get it.

Now that the service layer is all there, why do I need you?

The business of the service layer is only logic business, and it has to be done by me when it comes to normal business such as import and export.

Which one should be called in the service layer?

Find this interface ----- IUserService

This not only inherits the CRUD of the landlord MP, but also inherits all the business logic in the implementation class

 6.1 Create a controller package

6.2 Write the UserController class that calls the business layer

 first way of understanding

General formula for adding, deleting, modifying and checking methods:

    1

public  2   custom class name (    data type    4  of 4   )

   Return the current global service class. Methods in the service class ( 4 )

Methods in the service: check all: list , query by ID: getById , add and modify : saveOrUpdate , delete: removeById

1. Data query generally uses @GetMapping, data modification operation uses @PostMapping, and deletion uses @PostMapping.

Front end: I want to delete or query according to id,

Backend: Then you can just get and give me the id, and leave the rest to me, just add ("/{id}") after the comment . If you query all of them directly, you don’t even need to give me the id, I understand

Front end: I want to modify and add things, there are many fields of data

Backend: Then you can't put it in the request header, it's not safe, use post request, put it in the request body

2. This is the data that I hope the backend will give me. Just tell me whether it is successful for additions, deletions, or changes, so I use Boolean values. For query, you have to tell me what is found in the query, just use the attribute class name

3. This is related to 1. Post requests use @RequestBody, and others use @PathVariable to parse the id of the request header into json and send it to the backend

4. This also depends on 1. What data is sent by the front end, what data is used here. Nothing is written is all --- is the attribute class name

second way of understanding

@Note  ---This is the transmission definition that the front end wants to give to the back end

public wants the backend to give the frontend   a custom class name  (post annotation uses @RequestBody - otherwise    the data type    corresponds to the frontend)

         Return the current global service class. The method in the service class (the data type corresponds to the one passed from the front end)

package com.example.mybatis.controller;

import com.example.mybatis.entity.User;
import com.example.mybatis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/*
* 1.@RestController---添加控制层注解,让springboot知道这是控制层
* 2.@RequestMapping("/user")--- user代表默认访问路径在/user下可以访问
* */

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


    @Autowired  //4.自动注解
    private IUserService userService;  //3.定义调用服务层的接口


    /*
    *5.查询全部的数据
       5.1使用 @GetMapping注解,没有括号不定义就代表使用get方式,url访问上面默认路径/user
       5.2查询全部肯定使用的方法是集合<实体类>方式去自定义一个findAll方法名
       5.3再用服务层返回一个集合就好了
     */
    @GetMapping
    public List<User> findAll(){
        return userService.list();
    }


    /*6.根据id查询一条
      6.1查询使用@GetMapping注解,既然是根据id查询,那么就要把id传给后端。但是get是不能传递请求体的,
       只能传递请求头,那么只能把这个值放在请求头上面,就是这样("/{id}")放
      6.2自定义一个方法名(@PathVariable 类型 id),为什么要用id呢?这不是你前端这个"/{id}"说要吗
      @PathVariable这个注解的方式就是把请求头中的数字以Json传递给后端去识别,后端不能直接识别url上面的数字
      6.3 再用服务层返回获取id的方法就好了
    */
    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id){
        return userService.getById(id);
    }

    /*7.新增和修改
         需要传递body传递全部参数,
        7.1对数据的操作使用@PostMapping,括号里面不定义就代表使用post方式,url访问上面默认路径/user
        7.2自定义一个方法,括号里面使用(@RequestBody 属性类 自定义属性昵称)
        为什么这里用Boolean而不是User,因为对数据的修改希望返回的结果就两种,要么成功,要么失败,所以用布尔值
        @RequestBody这个注解用于映射传递来的json参数映射为到java对象里面,特别是适用与请求体的参数
        7.3然后再用服务层返回获取的saveOrUpdate方法就好了
    */
    @PostMapping
    public Boolean add(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    /*
    8.删除的方法
     8.1使用@DeleteMapping注解,因为删除只需要传递一个特定的id给后端就可以了,
     所以括号里面使用("/{id}")
     8.2创建一个自定义的方法,删除也是要么成功要么失败,所以使用Boolean作为返回值
     @PathVariable在上面已经解释过了
     8.3再用服务层次返回对应的方法,括号里面的值就是上面括号里面需要的值
    * */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id){
        return userService.removeById(id);
    }

}








/*    //修改数据的另一种写法
    @PostMapping("/update")
    public Boolean update(@RequestBody User user){
        return userService.updateById(user);
    }*/

At this point, the code is all written. If you don’t understand, go to the above code to show the diagram and comment explanation in advance.

MySQL ---> attribute class ---> data layer mapper interface ---> business service layer service interface ---> control layer (front-end and back-end interaction) 

According to the specification, interfaces cannot be called across levels, except for attribute classes

5. Front-end request test

The testing tool can use the built-in idea, or use postman and other request testing tools.

Postman official website download, install and log in detailed tutorial - Programmer Sought

specific test method

Postman test back-end additions, deletions, modifications and queries

Guess you like

Origin blog.csdn.net/m0_52861000/article/details/132247104