mybatis-plus

mybatis plus学习

入门流程

创建个数据库

1.创建数据库mybatis_plus及user表

id name age email
1 Jone 18 test1@baomidou.com
2 Jack 20 test2@baomidou.com
3 Tom 28 test3@baomidou.com
4 Sandy 21 test4@baomidou.com
5 Billie 24 test5@baomidou.com

对应的数据库脚本如下:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

对应的数据库脚本如下:

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

IDEA创建个SpringBoot项目

2.使用SpringBoot初始化一个项目

勾选初始SpringBoot项目:
- Lombok
- Spring Web
- Mybatis Framwork
- MySqL Driver

在pom下配置Mybatis-Plus配置

在pom文件<dependencies>下配置

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

在Application下添加注释

@MapperScan(“com.example.demo.mapper”)

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

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

}

创建pojo及子项目User实体类加注释@Date

package com.example.demo.pojo;

import lombok.Data;

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

创建mapper及子项目UserMapper接口并继承extends BaseMapper

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.springframework.stereotype.Repository;

@Repository//表示它是一个持久层
public interface UserMapper extends BaseMapper<User> {
}

测试

package com.example.demo;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.Wrapper;
import java.util.List;

@SpringBootTest
class DemoApplicationTests {

    //继承了BaseMapper,所有的方法都来自父类
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        //queryWrapper参数是一个条件构造器,这里先不设条件,用null值
        //查询全部用户
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);

    }

}

打印结果

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.1)

2021-12-02 15:24:13.061  INFO 12304 --- [           main] com.example.demo.DemoApplicationTests    : Starting DemoApplicationTests using Java 1.8.0_121 on DESKTOP-IFA4B36 with PID 12304 (started by BZ in D:\IntelliJ IDEA 2021.2.1\demo)
2021-12-02 15:24:13.062  INFO 12304 --- [           main] com.example.demo.DemoApplicationTests    : No active profile set, falling back to default profiles: default
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.4.0 
2021-12-02 15:24:15.195  WARN 12304 --- [           main] c.b.m.core.metadata.TableInfoHelper      : This primary key of "id" is primitive !不建议如此请使用包装类 in Class: "com.example.demo.pojo.User"
2021-12-02 15:24:15.338  INFO 12304 --- [           main] com.example.demo.DemoApplicationTests    : Started DemoApplicationTests in 2.549 seconds (JVM running for 3.478)
2021-12-02 15:24:15.580  INFO 12304 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-12-02 15:24:15.725  INFO 12304 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)
2021-12-02 15:24:15.786  INFO 12304 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-12-02 15:24:15.793  INFO 12304 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

配置日志

日志可以看到sql的具体执行

#数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#配置日志

> mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

测试查询


    //测试插入
    @Test
    public void testInsert(){
        User user=new User();

        user.setName("倩倩");
        user.setAge(20);
        user.setEmail("1321473656@qq.com");

        int insert = userMapper.insert(user);
        System.out.println(insert);
        System.out.println(user);
    }

主键自增策略

id实体类包装成包装类型的Long,


> IdType=
>     AUTO(0),//数据库id自增
>     NONE(1),//未设置主键
>     INPUT(2),//手动输入
>     ID_WORKER(3), //默认的,全局唯一id
>     ID_WORKER_STR(5),//ID_WORKER的字符串表示法
>     UUID(4),//全局唯一id,UUid
>     
测试更新
@Test
public void testUpdate(){

    User user=new User();
    user.setId(6L);//更新id为6的,类型为Long类型别忘了
    user.setAge(10);
    user.setEmail("1321473666@qq.com");
    User setAge;
    int i = userMapper.updateById(user);
    System.out.println(i);
}

自动填充、更新时间

创建时间、修改时间,这些操作需要自动化更新 所有的数据库表:gmt_create、gmt_modified要配置。

1.在表中新增字段create_time、update_tim

2.在实体类同步一下

> import java.util.Date;

@Data
public class User {
    @TableId(type = IdType.INPUT)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private Date CreateTime;
    private Date UpdateTime;
}



然后在实体类中加注解



    @TableField(fill= FieldFill.INSERT)
    private Date CreateTime;

    @TableField(fill=FieldFill.INSERT_UPDATE)
    private Date UpdateTime;


然后编写处理器处理这两个注解即可

package com.example.demo.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
}

上一篇:Caused by: java.lang.RuntimeException: java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ


下一篇:Mybatis-Plus