Mybatis Plus 快速入门

一、快速入门

1、建库建表

#创建用户表
CREATE TABLE user (
    id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
    name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
    age INT(11) DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
    manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id',
    create_time DATETIME DEFAULT NULL COMMENT '创建时间',
    CONSTRAINT manager_fk FOREIGN KEY (manager_id)
        REFERENCES user (id)
)  ENGINE=INNODB CHARSET=UTF8;

#初始化数据:
INSERT INTO user (id, name, age, email, manager_id
    , create_time)
VALUES (1087982257332887553, '大boss', 40, 'boss@baomidou.com', NULL
        , '2019-01-11 14:20:20'),
    (1088248166370832385, '王天风', 25, 'wtf@baomidou.com', 1087982257332887553
        , '2019-02-05 11:12:22'),
    (1088250446457389058, '李艺伟', 28, 'lyw@baomidou.com', 1088248166370832385
        , '2019-02-14 08:31:16'),
    (1094590409767661570, '张雨琪', 31, 'zjq@baomidou.com', 1088248166370832385
        , '2019-01-14 09:15:15'),
    (1094592041087729666, '刘红雨', 32, 'lhm@baomidou.com', 1088248166370832385
        , '2019-01-14 09:48:16');

2、引入依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
    </parent>

    <dependencies>
        <!--SpringBoot启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--SpringBoot test启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--lombok简化java代码-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--Mybatis-Plus启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--Mysql Jdbc驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

</project>

3、配置

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

4、编码

Application.java

package com.mp;

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

@SpringBootApplication
@MapperScan("com.mp.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

User.java

package com.mp.entity;

import lombok.Data;

import java.util.Date;
@Data
public class User {
    //主键
    private Long id;
    //姓名
    private String name;
    //年龄
    private int age;
    //邮箱
    private String email;
    //直属上级id
    private Long managerId;
    //创建时间
    private Date createTime;
}

UserMapper.java

package com.mp.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mp.entity.User;

public interface UserMapper extends BaseMapper<User> {
}

5、测试

SimpleTest.java

package com.mp;

import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class SimpleTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void select(){
        List<User> list = userMapper.selectList(null);
        list.forEach(System.out::println);
    }
}

测试 insert 语法

@Test
public void insert() {
    User user = new User();
    user.setName("刘明强");
    user.setAge(31);
    user.setManagerId(1088248166370832385L);
    user.setCreateTime(new Date());
    int rows = userMapper.insert(user);
    System.out.println("影响记录数:" + rows);
}

二、常用注解

注意上面的 insert 是可以成功插入数据的,但是代码中未给主键字段赋值,默认情况下,MP 会将类名称自动识别为数据库表名,对类中名为 id 的字段会自动识别是主键字段,而且 MP 自动识别驼峰形式的命名方式。

但现实情况,类名不等于数据库表名,而且主键字段也不一定叫 id,属性和数据库字段也不一定满足驼峰格式,对此,MP 也提供了解决方法。参考官网文档

@Data
@TableName("mp_user")
public class User {
    //主键
    @TableId
    private Long userId;
    //姓名
    @TableField("name")
    private String realName;
}

三、排除非表字段的三种方式

1、对属性加关键字 transient,使该属性不参入序列化

private transient String remark;

2、对属性加关键字 static,使之成为类变量

private static String remark;

3、使用@TableField(exist = false),标记数据库不存在该字段

@TableField(exist = false)
private String remark;

 

posted @ 2021-01-19 19:36  认真对待世界的小白  阅读(104)  评论(0编辑  收藏  举报