MybatisPlus


1 创建简单的demo

1.引入依赖

mybatis-plus-boot-starter、mysql-connector-java、lombok

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

2.创建实体类

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');
@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

3.创建配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    d: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&tinyInt1isBit=false

4.添加mapper接口

// 一定要写泛型User
@Repository
public interface UserMapper extends BaseMapper<User> {
}

5.启动类扫描mapper路径

@SpringBootApplication
@MapperScan("com.ll.mapper")
public class BootApplication {
	public static void main(String[] args) {
		SpringApplication.run(BootApplication.class, args);
	}
}

6.测试

@SpringBootTest
class BootApplicationTests {
	@Autowired
	UserMapper userMapper;
	@Test
	void test1() {
		System.out.println(userMapper.selectList(null));
	}
}

2 查看sql输出的日志

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

3 主键策略

1.自增
2.UUID
3.Redis
4.MP生成

    @TableId(type = IdType.ID_WORKER)
    private Long id;
  • AUTO:自动
  • INPUT:手动输入
  • NONE:不使用
  • UUID:随机字符串
  • ID_WORKER:根据算法生成全局序列(数字)
  • ID_WORKER_STR:根据算法生成全局序列(字符串)

4 自动填充

1、添加创建时间和更新时间的字段

ALTER TABLE `user` ADD COLUMN `create_time` datetime;
ALTER TABLE `user` ADD COLUMN `update_time` datetime;

2、修改相应bean
什么时候添加/更新时间

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

3、实现元对象处理器接口
往字段里面添加什么东西

@Component
public class handler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

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

5 MP实现乐观锁

  • 支持的数据类型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity 中
  • 仅支持 updateById(id) 与 update(entity, wrapper) 方法
  • 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
    1、数据库中添加version字段
ALTER TABLE `user` ADD COLUMN `version` INT

2、修改相应bean

    @Version
    @TableField(fill = FieldFill.INSERT)
    private int version;

3、实现元对象处理器接口

    @Override
    public void insertFill(MetaObject metaObject) {
        ...
        this.setFieldValByName("version",1,metaObject);
    }

4、添加乐观锁插件

@Configuration
public class MybatisConfig {
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

5、测试
测试乐观锁可以修改成功(先读后写):

	@Test
	void test1() {
		User user = userMapper.selectById(1L);
		System.out.println(user.toString());
		user.setName("张三");
		System.out.println(userMapper.updateById(user));
	}

测试乐观锁修改失败:

	@Test
	void test3() {
		User user = userMapper.selectById(1L);
		System.out.println(user.toString());
		user.setName("张三san");
		user.setVersion(user.getVersion()-1);
		System.out.println(userMapper.updateById(user));
	}

6 分页查询

1.添加分页插件

    @Bean
    public PaginationInterceptor paginationInnerInterceptor(){
        return new PaginationInterceptor();
    }

2.分页查询实现

	@Test
	void test5() {
		Page<User> page = new Page<>();
		page.setSize(2);
		page.setCurrent(1);
		userMapper.selectPage(page,null);
		System.out.println("总记录数:"+page.getTotal());
		List<User> users = page.getRecords();
		for (User user:users) {
			System.out.println(user);
		}
	}

7 逻辑删除

1.数据库中添加 deleted字段

ALTER TABLE `user` ADD COLUMN `deleted` boolean

2、修改相应bean

    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Integer deleted;

3、元对象处理器接口添加deleted的insert默认值

this.setFieldValByName("deleted",1,metaObject);

4、application.properties 加入配置

mybatis-plus:
  global-config:
    db-config:
      logic-delete-value: 0
      logic-not-delete-value: 1

5、在 MybatisPlusConfig 中注册 Bean

    @Bean
    public ISqlInjector iSqlInjector(){
        return new LogicSqlInjector();
    }

6、测试逻辑删除

	@Test
	void test7() {
		System.out.println(userMapper.deleteById(5L));
	}

数据库执行的语句是update

7、测试逻辑删除后的查询
查不到已经删除的数据

8 条件查询构造器 Wapper

  • EQ:等于 NE:不等于
  • GE:大于等于 GT:大于 LE:小于等于 LT:小于
  • like
  • between
  • orderByDesc
  • select:查询某几个字段
	@Test
	void test9() {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		// eq:等于  ne:不等于
		wrapper.eq("name", "Jone");
		wrapper.ne("age",20);
		List<User> users = userMapper.selectList(wrapper);
		for (User user:users) {
			System.out.println(user);
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值