【Mybatis】mybatis-plus 简单总结

新年快乐,新的一年我的座右铭是: 学习不是难事,难的是坚持每天学习!
在2020年好好规划自己,继续前进!

Mybatis Plus 简单总结

项目中常常会使用mybatis做orm框架,并且常常还会配合Mybatis plus使用。

什么是Mybatis Plus 呢?

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
简单说Mybatis Plus只是提高了开发人员的工作效率,真正和数据库进行交互的还是Mybatis。

Quick start

  1. 创建数据库mybatis_plususer
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, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
  1. 快速搭建一个Spring Boot 项目,并在pom.xml中加入以下依赖
       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
      <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
  1. 在application.properties中添加以下配置
# 因为我的电脑上下的是mysql 8.0版本,所以Driverclass 和url会和你们不一样
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
server.port=8081
# 打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  1. 创建User实体类
@Data // Lombok
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  1. 创建UserMapper
import com.amber.learnmore.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Component;

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

可以看到UserMapper继承了BaseMapper ,BaseMapper相当于Jpa中的Repository,为我们封装好了一些常用的方法。

  1. 编写Test方法
@SpringBootTest
class LearnmoreApplicationTests {
    @Autowired
    UserMapper userMapper;

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

Result:


User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])

是不是很简单呢,不需要自己动手写一些相对比较简单的SQL

Mybatis Plus Insert

  @Test
    void insert() {
        User user = new User();
        user.setName("Helen");
        user.setAge(16);
        user.setEmail("[email protected]");
        int result = userMapper.insert(user);
        System.out.println(result);
        System.out.println(user);
    }

Result:

1
User(id=1213699960072052738, name=Helen, age=16, [email protected])

可以发现已经插入成功,并且自动为id赋值。这是怎么回事呢?
因为MP自动为我们封装了IdWorker.java。相信学习过分布式的童鞋对于这个都不陌生。它会在我们插入的时候自己为主键Set值。那么如果我们不想使用idWork生成id怎么办呢?

id生成策略

修改User.java

    @TableId(type = IdType.AUTO)
    private Long id;

IdType可以以下6种:

    AUTO(0), 自增长
    NONE(1), 该类型为未设置主键类型
    INPUT(2), 自己输入
    ID_WORKER(3), 默认的,雪花算法生成id 
    UUID(4), UUID
    ID_WORKER_STR(5);  // 字符串全局唯一ID

Update

update其实也很简单

    @Test
    void update() {
        User user = userMapper.selectById(1);
        user.setName("amber");
        int i = userMapper.updateById(user);
        System.out.println(i);
    }

重点自动填充

在Insert 和update的时候,我们常常会默认插入create_time,update_time,is_deleted。
修改User表

ALTER TABLE `mybatis_plus`.`user` 
ADD COLUMN `create_time` DATETIME NULL AFTER `email`,
ADD COLUMN `update_time` DATETIME NULL AFTER `create_time`,
ADD COLUMN `is_deleted` TINYINT(1) NULL AFTER `update_time`;

添加UserMetaObjectHandler实现MetaObjectHandler

@Component
public class UserMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("isDeleted", false, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

添加User.java字段

    @TableField(fill = FieldFill.INSERT) // 表示插入的时候自动填充
    private Date createTime;
    @TableField(fill = FieldFill.UPDATE) // 更新的时候自动填充
    private Date updateTime;
    @TableField(fill = FieldFill.INSERT)
    private BooleanisDeleted;

再次运行insert和update方法就可以了

Delete

    @Test
    void delete() {
        // 公司里一般不这么用,一般都是逻辑删除
        userMapper.deleteById(3L);
    }

Select

其实select也很简单,只要看mybatis plus提供的方法就能明白

  1. 通过id查询
@Test
    public void testSelectById(){
​
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }
  1. 通过id批量查询
@Test
public void testSelectBatchIds(){
​
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}
  1. 条件查询通过Map
    @Test
    void testSelectByMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "helen");
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }
  1. 分页查询
@Test
    void testSelectByPage() {
        Page<User> page = new Page(1, 2);
        userMapper.selectPage(page, null);
        List<User> records = page.getRecords();
        records.forEach(System.out::println);
        System.out.println(page.getCurrent());//当前页
        System.out.println(page.getPages());//总页数
        System.out.println(page.getSize());//每页显示记录数
        System.out.println(page.getTotal());//总记录数
        System.out.println(page.hasNext());//是否有下一页
        System.out.println(page.hasPrevious());//是否有上一页
    }

猜你喜欢

转载自www.cnblogs.com/amberbar/p/12152305.html