官网地址:MyBatis-Plus
按照官方文档实现步骤:
1.首先我们创建数据库和表:
CREATE DATABASE mybatis_plus;
USE mybatis_plus;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');
2.创建一个springboot项目只需要添加web支持然后导入依赖:
尽量不要同时导入mybatis和mybatis-plus因为版本有差异!
mysql mysql-connector-java org.projectlombok lombok com.baomidou mybatis-plus-boot-starter 3.0.5
3.连接数据库和mybatis相同
# mysql 5 驱动不同 com.mysql.jdbc.Driver
# mysql 8 驱动不同 com.mysql.cj.jdbc.Driver . 需要增加时区的配置 serverTimezone=GMT%2B8
# DataSource Config
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8username: rootpassword: 201408181
4.编写我们的dao层的User类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private Long id;private String name;private Integer age;private String email;}
5.编写我们的mapper接口
//使用mybatis-plus后我们不用在写xml文件了,所有CRUD操作都已经编写完成了
// 在对应的mapper上面继承基本的类 BaseMapper
@Reference
public interface UserMapper extends BaseMapper {}
6.在主启动类MybatisPlusApplication
上扫描我们Mapper包下的所有接口
@MapperScan("com.jiu.mapper")
7.测试类中测试
@Autowiredprivate UserMapper userMapper;@Testvoid contextLoads() {//参数是一个Wrapper , 条件构造器,这里我们先不用 null//查询全部用户List users = userMapper.selectList(null);users.forEach(System.out::println);}
# 配置日志 (默认控制台输出)
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
再次测试就会输入配置文件
1.查询操作
@Testpublic void testSelectById() {//查询一个数据User user = userMapper.selectById(1L);System.out.println(user);}
@Testpublic void testSelectBatchIds() {;//查询多个数据List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));users.forEach(System.out::println);}
@Testpublic void testSelectBatchId() {;//条件查询HashMap map = new HashMap<>();map.put("name","白泽");map.put("age",20);List users = userMapper.selectByMap(map);users.forEach(System.out::println);}
2.插入数据
@Testpublic void testInsert() {User user = new User();user.setName("jiuqi");user.setAge(19);user.setEmail("2096253166@qq.com");int result = userMapper.insert(user);System.out.println(result);System.out.println(user);}
3.主键生成策略
雪花算法:
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0.几乎全球唯一
4.更新数据
sql语句是动态sql
@Testpublic void testUpdate() {User user = new User();user.setId(6L);user.setName("九七哟");user.setAge(20);user.setEmail("2096253166@qq.com");userMapper.updateById(user); //updateById()参数是 一个对象!}
5.自动填充
阿里巴巴开发手册:所有的数据库表:gmt_create .gmt_modified几乎所有的表都要配置上!而且需要自动化!
第一种方法:我们需要在数据库新增对应字段(一般不使用)
在实体类上也要加上新增的字段
private Date createTime;
private Date updateTime;
第二种方法:在代码上修改
@TableField(fill = FieldFill.INSERT)private Date creatseTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;
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 {@Overridepublic void insertFill(MetaObject metaObject) {log.info("start insert fill ....");this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {log.info("start update fill ....");this.setFieldValByName("updateTime",new Date(),metaObject);}
}
6.乐观锁悲观锁
乐观锁: 顾名思义十分乐观,他总是认为不会出现问题,无论干什么都不去上锁!如果出现了问题,再次更新值测试
悲观锁;顾名思义十分悲观,他总是认为出现问题,无论干什么都会上锁!再去操作!
乐观锁实现方式:
测试下乐观锁
@Versionprivate int version;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;@EnableTransactionManagement //自动管理事务,默认开启可以不用写
@MapperScan("com.jiu.mapper") //这是配置类我们可以把读取mapper文件的注解拿过来
@Configuration
public class MyBatisPlusConfig {@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();}
}
7.分页查询
//分页插件public PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
@Testpublic void testPage() {Page page = new Page<>(2, 5);userMapper.selectPage(page, null);page.getRecords().forEach(System.out::println);System.out.println(page.getTotal()); //获取查询的总数}
8.删除操作和查询操作一样,把select换成delete就行
9.逻辑删除
物理删除:从数据库中直接移除
逻辑删除: 在数据库中没有被移除,而是通过一个变量来让他失效! deleted=0=>deleted=1,执行的是一个update操作再次查询也没有这个数据,管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
@TableLogicprivate Integer del;
//注册逻辑删除
@Bean
public ISqlInjector sqlInjector(){return new LogicSqlInjector();
}
# 配置日志 (默认控制台输出)
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 配置逻辑删除global-cb-config:logic-delete-value: 1logic-not-delete-value: 0