您好,欢迎来到易榕旅网。
搜索
您的当前位置:首页MyBatis-Plus入门笔记(一)

MyBatis-Plus入门笔记(一)

来源:易榕旅网

在日常开发中我们需要实现大量CRUD功能代码,我们通常使用MyBatis-Plus进行简化开发。MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网:

1. 快速开始

1.1 引入依赖

准备一个springboot项目,引入数据库相关依赖,之后就可以开始整合MyBatisPlus

pox.xml文件中引入MybatisPlus相关依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.5.3.2</version>
</dependency>

由于这个依赖包含对MyBatis的自动装配,因此无需再引入MyBatis的依赖。

1.2 定义Mapper

MyBatisPlus提供了BaseMapper类,实现了基本的单表CRUD操作,如下图所示

所以我们要进行单表CRUD操作时无需再Mapper类中写相关方法实现,只需让Mapper类继承BaseMapper即可

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

1.3 配置

MyBatisPlus支持基于yaml文件的自定义配置

配置application.yaml文件,包括数据源、日志和MyBatisPlus相关配置:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 1234
logging:
  level:
    com.itheima: debug
  pattern:
    dateformat: HH:mm:ss
mybatis-plus:
  type-aliases-package: com.itheima.mp.domain.po # 别名扫描包
  mapper-locations: "classpath*:/mapper/**/*.xml" # Mapper.xml文件地址,当前这个是默认值。
  configuration:
    map-underscore-to-camel-case: true #是否开启下划线和驼峰的映射
    cache-enabled: false #是否开启二级缓存
  global-config:
    db-config:
      id-type: assign_id #id为雪花算法生成
      update-strategy: not_null #更新策略:只更新非空字段

更多的mp配置,请查阅官方文档:

1.4 测试

我新建了一个数据库名为mp,mp下新建表user,以下是相关sql语句

CREATE DATABASE IF NOT EXISTS `mp`;
USE `mp`;
CREATE TABLE `user` (
	`id` BIGINT(19) NOT NULL AUTO_INCREMENT COMMENT '用户id',
	`username` VARCHAR(50) NOT NULL COMMENT '用户名' COLLATE 'utf8_general_ci',
	`password` VARCHAR(128) NOT NULL COMMENT '密码' COLLATE 'utf8_general_ci',
	`phone` VARCHAR(20) NULL DEFAULT NULL COMMENT '注册手机号' COLLATE 'utf8_general_ci',
	`info` JSON NOT NULL COMMENT '详细信息',
	`status` INT(10) NULL DEFAULT '1' COMMENT '使用状态(1正常 2冻结)',
	`balance` INT(10) NULL DEFAULT NULL COMMENT '账户余额',
	`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
	`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
	PRIMARY KEY (`id`) USING BTREE,
	UNIQUE INDEX `username` (`username`) USING BTREE
)
COMMENT='用户表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT
AUTO_INCREMENT=5;
INSERT INTO `user` (`id`, `username`, `password`, `phone`, `info`, `status`, `balance`, `create_time`, `update_time`) VALUES
	(1, 'Jack', '123', '13900112224', '{"age": 20, "intro": "佛系青年", "gender": "male"}', 1, 1600, '2023-05-19 20:50:21', '2023-06-19 20:50:21'),
	(2, 'Rose', '123', '13900112223', '{"age": 19, "intro": "青涩少女", "gender": "female"}', 1, 600, '2023-05-19 21:00:23', '2023-06-19 21:00:23'),
	(3, 'Hope', '123', '13900112222', '{"age": 25, "intro": "上进青年", "gender": "male"}', 1, 100000, '2023-06-19 22:37:44', '2023-06-19 22:37:44'),
	(4, 'Thomas', '123', '17701265258', '{"age": 29, "intro": "伏地魔", "gender": "male"}', 1, 800, '2023-06-19 23:44:45', '2023-06-19 23:44:45');

编写测试类UserMapperTest,之后的单元测试都放到该类下

@SpringBootTest
class UserMapperTest {
    @Autowired
    private UserMapper userMapper;
   	//测试代码
}

编写插入数据的单元测试

@Test
void testInsert() {
    User user = new User();
    user.setId(5L);
    user.setUsername("Lucy");
    user.setPassword("123");
    user.setPhone("18688990011");
    user.setBalance(200);
    user.setInfo("{\"age\": 24, \"intro\": \"英文老师\", \"gender\": \"female\"}");
    user.setCreateTime(LocalDateTime.*now*());
    user.setUpdateTime(LocalDateTime.*now*());
    userMapper.insert(user);
}

测试结果

查询操作

 @Test
void testSelectById() {
    User user = userMapper.selectById(5L);
    System.out.println("user = " + user);
}

测试结果

@Test
void testQueryByIds() {
    List<User> users = userMapper.selectBatchIds(List.of(1L, 2L, 3L, 4L));
    users.forEach(System.out::println);
}

测试结果

修改数据

@Test
void testUpdateById() {
    User user = new User();
    user.setId(5L);
    user.setBalance(20000);
    userMapper.updateById(user);
}

测试结果

@Test
void testDeleteUser() {
    userMapper.deleteById(5L);
}

测试结果

2. 常见注解

下面列举了三个最常用的注解和它们的常用属性

2.1 @TableName

  • 描述:表名注解,标识实体类对应的表
  • 使用位置:实体类
@TableName("sys_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

2.2 @TableId

  • 描述:主键注解
  • 使用位置:实体类主键字段
@TableName("sys_user")
public class User {
    @TableId
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

常用属性:

  • value : 主键字段名
  • type : 指定主键类型
    • IdType.NONE 无状态
    • IdType.AUTO 数据库 ID 自增
    • IdType.INPUT insert 前自行 set 主键值
    • IdType.ASSIGN_ID 雪花算法(默认)

2.3 @TableField

  • 描述:字段注解(非主键)
@TableName("sys_user")
public class User {
    @TableId
    private Long id;
    @TableField("nickname")
    private String name;
    private Integer age;
    private String email;
}

常用属性:

  • value : 数据库字段名
  • exist : 是否为数据库表字段

以上只列举了我目前用过的,更多注解和属性查阅官方文档:

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrd.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务