Integration and use of mybatis-plus+springboot

Integrate mybatis-plus

1. Installation

Maven:

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus-boot-starter</artifactId>    <version>3.4.3</version></dependency>

2. Configuration

Spring Boot project:

  • application.yml Add the relevant configuration of the H2 database in the  configuration file:
# DataSource Configspring:  datasource:    driver-class-name: org.h2.Driver    schema: classpath:db/schema-h2.sql    data: classpath:db/data-h2.sql    url: jdbc:h2:mem:test    username: root    password: test
  • Configure MapperScan annotations
@[email protected]("com.baomidou.mybatisplus.samples.quickstart.mapper")public class Application {     public static void main(String[] args) {        SpringApplication.run(Application.class, args);    } }

3. Annotation

Reference website: mybaitis-plus

Annotation usage: one-to-one correspondence between entity classes and database fields

user.java

package com.example.mybatisplus.bean; import com.baomidou.mybatisplus.annotation.TableField;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor; @[email protected]@NoArgsConstructorpublic class User {    private int id;    @TableField("userName")    private String userName;    @TableField("passWord")    private String passWord;    @TableField("realName")    private String realName;}

Directory Structure

4. Coding:

user.java

package com.example.mybatisplus.bean; import com.baomidou.mybatisplus.annotation.TableField;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor; @[email protected]@NoArgsConstructorpublic class User {    private int id;    @TableField("userName")    private String userName;    @TableField("passWord")    private String passWord;    @TableField("realName")    private String realName;}

UserMapper.java

UserMapper inherits the implementation class from mybatis-plus (addition, deletion, modification, check), so you don’t need to write the implementation class.
If you want to customize the mapper method, the method is the same as mybatis, please refer to another article about the addition, deletion and modification under the environment of mybaitis+springbootd
package com.example.mybatisplus.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.mybatisplus.bean.User;import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapperpublic interface UserMapper extends BaseMapper<User> {   public List<User> findall();}

Test code

 @Test    void contextLoads() {        List<User> users = userMapper.selectList(null);        for (User user : users) {            System.out.println("user = " + user);        }    }

operation result