MybatisPlus - [02] HelloWorld
参考:https://www.cnblogs.com/haoxinyue/p/5208136.html(分布式系统唯一ID生成方案汇总)
一、准备工作
(1)创建数据库:
create database if not exists mybatis_plus;
(2)创建user表:
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)
);
创建一张表必须拥有的字段:
① version(乐观锁)
② deleted(逻辑删除标志)
③ gmt_create(创建时间)
④ gmt_modified(修改时间)
(3)插入数据
insert into user (id,name,age,email) values
(1,'宇智波鼬',24,'you.yuzhibo@xiao.com'),
(2,'飞段',27,'duan.fei@xiao.com'),
(3,'角都',32,'du.jiao@xiao.com'),
(4,'迪达拉',23,'dala.di@xiao.com'),
(5,'蝎',18,'xie@xiao.com'),
(6,'干沛鬼鲛',28,'guijiao.ganpei@xiao.com'),
(7,'佩恩天道',26,'tiandao.pain@xiao.com'),
(8,'佩恩畜生道',26,'chushengdao.pain@xiao.com'),
(9,'佩恩修罗道',26,'xiuluodao.pain@xiao.com'),
(10,'佩恩恶鬼道',26,'eguidao.pain@xiao.com'),
(11,'佩恩人间道',26,'renjiandao.pain@xiao.com'),
(12,'佩恩地狱道',26,'diyudao.pain@xiao.com'),
(13,'小南',26,'nan.xiao@xiao.com'),
(14,'漩涡长门',28,'changmen.xuanwo@xiao.com');
二、测试
(1)创建一个SpringBoot项目:mybatis-plus
(2)Maven依赖配置
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.4</version>
</dependency>
(3)application.properties
配置
spring.application.name=mybatis-plus
# 数据库连接配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&userUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=!QAZ2wsx
# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(4)POJO类
package com.harley.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author harley
* @date 2024/06/06 17:30
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
(5)Mapper类
package com.harley.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.harley.pojo.User;
import org.springframework.stereotype.Repository;
/**
* @author harley
* @since 2024-06-06 21:46:57
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}
(6)主类配置MapperScan包扫描
package com.harley;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.harley.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
(7)测试类
package com.harley;
import com.harley.mapper.UserMapper;
import com.harley.pojo.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
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
(8)控制台打印结果
(9)application.properties中配置日志之后,控制台会打印如下内容
三、CURD(Create Update Read Delete)
(1)insert
@Test
void testInsert(){
User user = new User(16L,"黑绝",200,"jue.hei@xiao.com");
int res = userMapper.insert(user);
if(res > 0){
System.out.println("数据插入成功");
}
}
(2)insert(不设置主键)
@Test
void testInsert(){
User user = new User();
user.setName("白绝");
user.setAge(119);
user.setEmail("jue.bai@xiao.com");
int res = userMapper.insert(user);
if(res > 0){
System.out.println("数据插入成功");
}
}
如图
1798726048819458049
为雪花算法生成的long型ID
(3)update
根据条件自动拼接动态SQL
@Test
void testUpdate(){
User user = new User(16L,"绝",199,"jue@xiao.com");
int res = userMapper.updateById(user);
if(res > 0){
System.out.println("数据更新成功");
}
}
(3)select
- 通过ID查询
@Test
void testSelectById(){
User user = userMapper.selectById(100861103L);
System.out.println(user);
}
- 批量查询
@Test
void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L));
users.forEach(System.out::println);
}
- 条件查询
@Test
void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","小南");
map.put("age",26);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
(4)delete
- 根据id删除
@Test
void testDeleteById(){
User user = new User();
user.setId(100861103L);
int res = userMapper.deleteById(user);
System.out.println(res);
}
- 批量删除
@Test
void testDeleteBatchId(){
int res = userMapper.deleteBatchIds(Arrays.asList(100861100, 100861101, 100861102));
if (res > 0){
System.out.println("删除成功");
}
}
- 条件删除
/**
* 生成20只白绝
*/
@Test
void testInsert(){
int i = 1;
while(i<21) {
User user = new User();
user.setName("白绝");
user.setAge(21);
user.setEmail("jue.bai@xiao.com");
int res = userMapper.insert(user);
if (res > 0) {
System.out.println("生成"+i+"只白绝.");
}
i++;
}
}
@Test
void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","白绝");
int res = userMapper.deleteByMap(map);
if (res > 0){
System.out.println("消灭"+res+"只白绝");
}
}
批量生成20只白绝之前,已经有3只白绝。
四、不同的主键策略
IdType的集中类型
public enum IdType {
AUTO(0), // 数据库id自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入
ASSIGN_ID(3),
ASSIGN_UUID(4); // 全局唯一的ID
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
4.1、IdType.AUTO
(1)实体类字段上配置 @TableId(type = IdType.AUTO)
package com.harley.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @author harley
* @date 2024/06/06 17:30
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
(2)数据库中的主键设置自增
(3)可以先在数据库中测试
insert into user (name,age,email) values ('漩涡香菱',16,'xianglin.xuanwo@xiao.com');
(4)测试类进行insert测试
@Test
void testInsert(){
User user = new User();
user.setName("大蛇丸");
user.setAge(32);
user.setEmail("shewan.da@xiao.com");
int res = userMapper.insert(user);
if (res > 0){
System.out.println("数据插入成功!");
}
}
数据库中的数据则是......
4.2、IdType.INPUT
(1)修改类型为INPUT
@TableId(type = IdType.INPUT)
private Long id;
(2)测试类
@Test
void testInsert(){
User user = new User();
user.setName("重吾");
user.setAge(18);
user.setEmail("wu.zhong@xiao.com");
int res = userMapper.insert(user);
if (res > 0){
System.out.println("数据插入成功!");
}
}
数据库中则是
五、自动填充
创建时间、修改时间!这些操作一般都是自动化完成的,不希望手动更新。
阿里巴巴开发手册中所有的数据库表都有
gmt_create
(创建时间)、gmt_modified
(修改时间)这两个字段注:gmt是格林尼治标准时间的缩写
5.1、在数据库中配置
(1)在表中新增字段create_time
、update_time
alter table user add column create_time datetime default current_timestamp comment '创建时间';
alter table user modify column update_time datetime default current_timestamp on update current_timestamp comment '修改时间';
(2)将数据库中字段的变更同步到POJO类
package com.harley.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
/**
* @author harley
* @date 2024/06/06 17:30
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
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; // 更换为驼峰标识
}
(3)测试更新方法,将表中ID
为100861102
的name
和email
进行更新,查看create_time
和update_time
的变化
@Test
void testUpdate(){
User user = new User();
user.setId(100861102L);
user.setName("宇智波佐助");
user.setEmail("zuozhu.yuzhibo@xiao.com");
userMapper.updateById(user);
}
(4)观察到update_time随着更新操作的执行,变更为最新的时间。
5.2、在代码进行处理
(1)将create_time、update_time的默认值去掉,update_time的自动更新也去掉
alter table user modify create_time datetime comment '创建时间';
alter table user modify update_time datetime comment '修改时间';
(2)给需要自动填充的属性添加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
(3)编写处理器处理注解
package com.harley.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;
/**
* @author harley
* @date 2024/06/07 15:24
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/**
* 插入时的填充策略
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill......");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
/**
* 更新时的填充策略
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill......");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
(4)测试类中进行insert和update操作,观察create_time、update_time的变化。
@Test
void testInsert(){
User user = new User();
user.setName("重吾666");
user.setAge(21);
user.setEmail("wu.zhong@xiao.com");
int res = userMapper.insert(user);
if (res > 0){
System.out.println("数据插入成功!");
}
}
@Test
void testUpdate(){
User user = new User();
user.setId(100861103L);
user.setName("zhongwu");
userMapper.updateById(user);
}
六、idea界面
— 业精于勤荒于嬉,行成于思毁于随 —