MyBatis-Plus Overview

table of Contents

1 pom.xml

2 application.properties

3 startup class

4 Model

5 Mapper

6 Service

7 test class


MyBatis MyBatis-Plus is an enhancement tool for enhancing not only change the basis on MyBatis, to simplify development, increase efficiency and health. Use it the same as using Hibernate, only the method for calling a single table operations without writing SQL database corresponding to complete the operation quickly save a lot of development time. For multi-table operation, or write their own SQL when writing SQL can also be achieved with the original method of MyBatis.


1 pom.xml

I use the Spring Boot 2.2.4.RELEASE, the depending follows (wherein Lombok is introduced, to simplify the programming of the Java Model, see author another article "Overview Lombok is" ):

<?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 https://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.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hys</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis-plus</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</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
    </dependencies>

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

</project>

2 application.properties

I use a database MySQL 8.0.13, the associated connection configuration is shown below (you can also configure the extended configuration MyBatis-Plus, for example, the primary key increment strategies, the tombstone and so on. Here are just demo, you have chosen the default configuration ):

#MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/user?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

3 startup class

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

@SpringBootApplication
@MapperScan("com.hys.mybatisplus.mapper")
public class MybatisPlusApplication {

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

}

Add @MapperScan notes on startup class, in order to scan Mapper layer. Of course, you can also add notes in each @Mapper Mapper interface, the effect is the same.


4 Model

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("user")
public class User implements Serializable {

    private static final long serialVersionUID = -288816356037467194L;

    @TableId
    private Long userId;

    private String name;

    private Integer age;

    private String email;
}

And wherein @TableName @TableId MyBatis-Plus annotations are used to represent the name of the database table and the primary key.


5 Mapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hys.mybatisplus.model.User;

public interface UserMapper extends BaseMapper<User> {
}

6 Service

import com.baomidou.mybatisplus.extension.service.IService;
import com.hys.mybatisplus.model.User;

public interface UserService extends IService<User> {
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.mybatisplus.mapper.UserMapper;
import com.hys.mybatisplus.model.User;
import com.hys.mybatisplus.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

7 test class

Here are some uses, full-featured examples refer to the official documentation.

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hys.mybatisplus.model.User;
import com.hys.mybatisplus.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    void mybatisPlusTest() {
        //增
        User user = User.builder().name("Robert Hou").age(24).email("[email protected]").build();
        userService.save(user);

        List<User> list = new ArrayList<>();
        list.add(User.builder().name("Emma").age(24).email("[email protected]").build());
        list.add(User.builder().name("Joyce").age(18).email("[email protected]").build());
        list.add(User.builder().name("Wilson").age(28).email("[email protected]").build());
        userService.saveBatch(list, 1000);

        //改
        user.setAge(25);
        userService.updateById(user);

        list.forEach(item -> item.setAge(item.getAge() + 1));
        userService.updateBatchById(list, 1000);

        user.setAge(26);
        userService.lambdaUpdate().eq(User::getName, "Robert Hou").update(user);

        //查
        User byId = userService.getById(1226475999890317314L);
        System.out.println(byId);

        User robert_hou = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getName, "Robert Hou"));
        System.out.println(robert_hou);

        List<User> robert_hou1 = userService.lambdaQuery().eq(User::getName, "Robert Hou").list();
        robert_hou1.forEach(System.out::println);

        List<Long> userIdList = list.stream().map(User::getUserId).collect(Collectors.toList());
        userService.listByIds(userIdList);

        //删
        userService.removeById(6);

        userService.removeByIds(userIdList);

        userService.remove(new QueryWrapper<User>().lambda().eq(User::getName, "3234"));
    }

}

 

Published 64 original articles · won praise 82 · views 70000 +

Guess you like

Origin blog.csdn.net/weixin_30342639/article/details/104237047