Spring boot series tutorials mybatisplus integration

Time:2020-3-7

Spring boot series tutorials mybatisplus integration

191231 spring boot series tutorial mybatisplus integration

In the previous section, we introduced the operation of adding, deleting, modifying and querying dB by integrating mybatis with springboot, and provided two ways to implement mapper interface: XML and annotation. Although the annotation method killed the XML file, it was not elegant to use. In this paper, we will introduce the use case of mybats plus to simplify the conventional crud operation

<!– more –>

I. environment

This article uses the spring boot version as2.2.1.RELEASE, mybatis plus version is3.2.0, the database is MySQL 5+

1. Project construction

It is recommended to use the official tutorial to create a spring boot project. If you create a maven project directly, copy the following configuration content to yourpom.xmlin

  • The main introduction ismybatis-spring-boot-starterTo reduce choking
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.2.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

2. Configuration information

stayapplication.ymlIn the configuration file, add the relevant configuration of DB

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password:

Next, prepare a test table (still borrowing the table structure from the previous DB operation series blog post) for the subsequent curd; the table result information is as follows

DROP TABLE IF EXISTS `money`;

CREATE TABLE `money` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Name ` varchar (20) not null default '' comment 'user name',
  `How much is money ` int (26) not null default '0' comment ',
  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',
  `Create "at ` timestamp not null default current ` timestamp comment 'creation time',
  `Update "at ` timestamp not null default current" timestamp on update current "timestamp comment 'update time',
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2. Instance integration

There are some differences in using posture between mybatis plus and mybatis. The following is no helpgeneratorCase of direct manual code

1. PO

Create Po object corresponding to the table:MoneyPo

@Data
public class MoneyPo {
    private Integer id;

    private String name;

    private Long money;

    private Integer isDeleted;

    private Timestamp createAt;

    private Timestamp updateAt;
}

2. Dao interface

Different from mybatis, the operation interface of table inheritsBaseMapperAfter that, it comes with a single table curd operation interface, which basically does not need to define additional interfaces to realize DB interaction

public interface MoneyMapper extends BaseMapper<MoneyPo> {
}
  • Be carefulBaseMapperThe parameter of is the Po object corresponding to the table

3. test

After the above is completed, the integration process is basically finished. That’s right. It’s so simple. Next, we enter the test phase

First, the startup class, we added@MapperScanAnnotation, so there is no need to add@MapperAnnotated

@SpringBootApplication
@MapperScan("com.git.hui.boot.mybatisplus.mapper")
public class Application {

    public Application(MoneyRepository repository) {
        repository.testMapper();
    }

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

About the test case, the following will demonstrate four basic crud operation cases, because the focus of this article is not to introduce the usage of mybatis plus. For those who have questions about the following code, please refer to the official document: https://mp.baomidou.com/guide/

@Component
public class MoneyRepository {
    @Autowired
    private MoneyMapper moneyMapper;

    private Random random = new Random();

    public void testDemo() {
        MoneyPo po = new MoneyPo();
        po.setName("mybatis plus user");
        po.setMoney((long) random.nextInt(12343));
        po.setIsDeleted(0);

        //Add a piece of data
        moneyMapper.insert(po);

        // query
        List<MoneyPo> list =
                moneyMapper.selectList(new QueryWrapper<MoneyPo>().lambda().eq(MoneyPo::getName, po.getName()));
        System.out.println("after insert: " + list);

        // modification
        po.setMoney(po.getMoney() + 300);
        moneyMapper.updateById(po);
        System.out.println("after update: " + moneyMapper.selectById(po.getId()));

        // delete
        moneyMapper.deleteById(po.getId());

        // query
        Map<String, Object> queryMap = new HashMap<>(2);
        queryMap.put("name", po.getName());
        System.out.println("after delete: " + moneyMapper.selectByMap(queryMap));
    }
}

Output result

Spring boot series tutorials mybatisplus integration

II. other

0. project

  • Project: https://github.com/liuyueyi/spring-boot-demo
  • Example: https://github.com/liuyueyi/spring-boot-demo/blob/master/spring-boot/105-mybatis-plus

1. A grey blog

The best letter is not as good as the above. It’s just a one-of-a-kind remark. Due to the limited personal ability, there are inevitably omissions and mistakes. If you find a bug or have better suggestions, you are welcome to criticize and correct. Thank you very much

Here is a grey personal blog, recording all the blogs in study and work. Welcome to visit

  • One gray blog https://blog.hhui.top
  • Http://spring.hhui.top

Spring boot series tutorials mybatisplus integration