编程知识 cdmana.com

[mybatis plus] crud is an essential medicine and a good partner of mybatis

Do development , It is inevitable to add, delete, modify and check the data , that mybatis-plus I think it suits me very well java Novice , Simple to use .
The official website is here

One 、 What is? mybatis-plus

MyBatis-Plus( abbreviation MP), It's a MyBatis Enhanced tools for , stay MyBatis On the basis of that, only enhancement Do not change , To simplify development 、 Increase efficiency .
Anything that can use mybatis Conduct crud, And support standards sql The database of ,mp All of them can do .

Two 、 characteristic

  • No intrusion : Just enhance and don't change , The introduction of it will not affect the existing project , Silky smooth
  • Low loss : Start up will automatically inject basic CURD, No loss in performance , Direct object-oriented operation
  • Powerful CRUD: Built in universal Mapper、 Universal Service, Only a small amount of configuration can realize most of the single table CRUD operation , More powerful conditional constructors , Meet all kinds of use needs
  • Support Lambda Form call : adopt Lambda expression , Convenient compilation of various query conditions , No need to worry about wrong field writing
  • Support automatic generation of primary key : Support up to 4 Primary key policies ( Including distributed uniqueness ID generator - Sequence), Freely configurable , Solve the primary key problem perfectly
  • Support ActiveRecord Pattern : Support ActiveRecord Form call , Entity classes only need to inherit Model Class for powerful CRUD operation
  • Support custom global common operations : Support global common method injection ( Write once, use anywhere )
  • Built in code generator : Use code or Maven Plug in can be generated quickly Mapper 、Model 、Service 、Controller Layer code , Support template engine , More custom configurations
  • Built in paging plug-in : be based on MyBatis Physical paging , Developers don't need to worry about specific operations , After the plug-in is configured , Write paging is equivalent to normal List Inquire about
  • Paging plug-ins support multiple databases : Support MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer Etc
  • Built in performance analysis plug-in : Can output Sql Statement and its execution time , It is recommended to enable this feature when developing tests , Can quickly find out the slow query
  • Built in global interception plug-in : Provide full tables delete 、update Operation intelligence analysis blocking , You can also customize interception rules , Prevent misoperation

3、 ... and 、 Have a try

Since it's here to manipulate data , You have to prepare the data environment .

1. Building database 、 Build table 、 Building data

#  Create database 
CREATE DATABASE mybatis_plus;

#  Create table 
DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT ' Primary key ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT ' full name ',
	age INT(11) NULL DEFAULT NULL COMMENT ' Age ',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT ' mailbox ',
	PRIMARY KEY (id)
);

#  insert data 
INSERT INTO user (id, name, age, email) VALUES
(1, 'wesson1', 18, 'pingguotest1@pingguo.com'),
(2, 'wesson2', 19, 'pingguotest1@pingguo.com'),
(3, 'wesson3', 20, 'pingguotest1@pingguo.com'),
(4, 'wesson4', 22, 'pingguotest1@pingguo.com'),
(5, 'wesson5', 20, 'pingguotest1@pingguo.com');

2.idea Create project 、 To configure

For convenience , You can create a new Spring Initializr engineering .

To configure pom.xml file , You can modify springboot Version of , We use the stable version of 2.2.1.RELEASE.

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

Then add maven rely on .

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--lombok  Simplify entity classes -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

    </dependencies>

also , stay idea In the installation lombok plug-in unit . To settings in plugin Next , Search for lombok enter , Can be installed .

3. Configuration database

find application.properties file , The path is shown in the figure ,

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://119.45.240.254:3306/mybatis_plus?characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=swk080963

#mybatis journal , You can see the operation log on the console 
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Be careful : What we use here is mysql8,springboot2.1 Version above , Integrated 8.0 Version of jdbc drive , stay url Add the suffix ?characterEncoding=UTF-8&serverTimezone=GMT%2B8.
in addition ,driver-class-name It is also suggested that cj,com.mysql.cj.jdbc.Driver. Because of the previous com.mysql.jdbc.Driver It's abandoned , When running, there will be warning.

4. Write preparation code

Before we do that , There's still some preparation code that needs to be done :

entity Under bag user.java
package com.pingguo.mpdemo.entity;
import lombok.Data;

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Add... Here @Data Annotations can be , Don't write it manually set、get、tostring The method .

mapper Under bag UserMapper.java
package com.pingguo.mpdemo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pingguo.mpdemo.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {
}

This is a mapper Interface , We want to inherit BaseMapper, hold User The entity goes in , You can use crud 了 .

Configure scan mapper The path of

On the startup class , Add a note ,mapper The path of .

package com.pingguo.mpdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//  Configure scan mapper The path of 
@MapperScan("com.pingguo.mpdemo.mapper")
public class MpdemoApplication {

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

}

5. Write test code

For convenience , It can be done directly in the unit test code crud operation .

Inquire about

Because we've already inserted data into the table , So now you can look up all the data .

@SpringBootTest
class MpdemoApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
     void findAll() {
        List<User> users =  userMapper.selectList(null);
        System.out.println(users);
    }

}

Because we configured mybatis Log , So you can see the whole operation process in the console .

newly added 、 modify 、 Delete
//     newly added 
    @Test
    void addUser() {
        User user = new User();
        user.setName("pingguo");
        user.setAge(21);
        user.setEmail("pingguo@pingguo.com");
        userMapper.insert(user);
    }
//     Delete 
    @Test
    void deleteUser() {
        userMapper.deleteById(1L);
    }

//     modify 
    @Test
    void updateUser() {
        User user = new User();
        user.setId(2L);
        user.setName(" Modify name 222");
        userMapper.updateById(user);

    }

newly added 、 Delete 、 It's easy to modify , You can see the execution process through the log .

That's through mp Realize simple addition, deletion, modification and search , Very convenient , The rest goes on .

版权声明
本文为[Bite the apple and cry]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152542983m.html

Scroll to Top