脚本宝典收集整理的这篇文章主要介绍了狂神说MybatisPlus,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
需要的基础
为什么学习?
mybatisplus可以节省大量的时间,所有的CRUD代码都可以自动化完成!
为简化开发而生,简化mybatis
特性
链接:快速开始地址
使用第三方组件:
创建数据库
CREATE DATABASE mybatis_plus;
创建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等
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');
项目初始化,使用springboot
导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
</dependencies>
说明:我们使用Mybatisplus可以节省大量代码,尽量不要同时导入mybatis和mybatisplus!版本差异!
数据库连接
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
# mysql8注意配置时区
传统方式:pojo-DAO(连接mybatis/配置mapper)-service-controller
使用mybatis-plus之后
package edu.pojo;
import lombok.AllargsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id; // 必须是Long,得是long的包装类才能自动生成
private String name;
private int age;
private String email;
}
id类型必须为Long(long的包装类)才能使用雪花算法自动生成唯一id
package edu.mapper;
import com.baomidou.mybatisplus.core.mapper.BaSEMapper;
import edu.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/*
* 在对应的mapper上面继承基本的 BaseMapper
* 之后所有的crud都已经编写完成
* 不需要配置一堆文件了
* */
@Repository
public interface UserMapper extends BaseMapper<User> {
}
package edu;
import edu.mapper.UserMapper;
import edu.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 {
/*
* 基本方法父类的basemapper都已经实现了,我们也可以写自己的方法
* */
@Autowired
private UserMapper mapper;
@Test
void contextLoads() {
/*
* 参数是一个wapper,是一个条件编辑器
* */
final List<User> list = mapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
}
需要在启动类上扫描mapper包下的所有接口
package edu;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* 扫描mapper包
* */
@;mapperScan("edu.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
思考
我们所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志
配置基本的日志
# 配置日志
mybatis-plus:
configuration:
LOG-impl: org.apache.ibatis.logging.stdout.StdOutImpl
也可以使用其他类型的日志,导入相应的包即可
结果
配置完日志之后,就要注意这个自动生成的sql
/*
* 插入测试
* */
@Test
public void test01() {
User user = new User();
/*
* 自动帮我们生成id
* */
user.setName("kuku");
user.setAge(3);
user.setEmail("2062248305@QQ.com");
final int insert = mapper.insert(user);
System.out.println(insert);
/*
* 发现id会自动回填
* */
System.out.println(user);
}
数据库插入的id默认值为:全局唯一id
雪花算法:
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心(北京,上海等),5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。雪花算法支持的TPS可以达到419万左右(2^22*1000)。
mybatis-plus提供的主键策略
AUTO(0), // 自增,同时需要数据库中也配置自增
NONE(1), // 该类型为未设置主键类型
INPUT(2), // 用户输入,和数据库中类型保持一致即可
ASSIGN_ID(3), // 雪花算法,全局唯一id,数据库中类型必须为数值类型
ASSIGN_UUID(4); // 全局唯一uuid
说明:在新版的mybatis-plus中,主键策略默认为NONE,也就是使用雪花算法,同时取消了ID_WORKER_STR(5);
如何配置主键策略
在主键上使用@Tableid(type = IdType.ASSIGN_ID)
,然后根据需要修改type即可
也可以使用配置文件进行配置
mybatis-plus:
global-config:
db-config:
id-type: assign_id
测试
/*
* 测试更新
* */
@Test
public void test02() {
User user = new User();
user.setId(0l);
user.setName("kuku-sama");
user.setAge(3);
user.setEmail("2062248305@qq.com");
mapper.updateById(user);
}
// 在basemapper中的样式,需要传进去一个对象
int updateById(@Param("et") T entity);
注意:参数是一个对象
通过条件动态拼接sql
所有sql都是动态配置的
比如创建时间,修改时间!这些操作都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有数据库必须包括得到字段gmt_create,gmt_modified几乎所有的表都要配置,而且需要自动化!
方式一:数据库级别
方式二:代码级别
/*
* 字段添加需要填充的内容
* */
@TableField(fill = FielDFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
package edu.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;
@Slf4j
@Component // 将处理器加入到ioc容器中
public class MyDateHandler implements MetaObjectHandler {
/*
* 插入时填充策略
* */
@override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill");
//default MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
/*
* 更新时填充策略
* */
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill");
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
更新同时也改变了时间,不再展示图片
乐观锁在面试中经常问到。悲观锁,这个同时也容易问到。
乐观锁:顾名思义,十分乐观,总是认为不会出现问题,无论干什么都不去上锁。如果出现了问题,就再次更新值测试,经常采用version字段来判断。
悲观锁:顾名思义,十分悲观,他总是认为出现问题,无论干什么都会上锁,然后再进行操作。
主要讲解乐观锁机制
乐观锁实现机制
总的来说就是:先查询获得版本号,更新的时候带上这个version,如果执行更新时的version不等于查询时的version,就不执行更新,反之就执行更新操作,同时更新version的值。
测试MP中的乐观锁插件
// 使用mybatisplus下的version注解
@Version
private Integer version;
package edu.config;
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;
/*
* 配置类
* */
@MapperScan("edu.mapper")
@Configuration
public class MybatisPlusConfig {
/*
* 注册乐观锁插件
* */
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
/*
* 乐观锁:成功
* */
@Test
public void test03() {
// 查询用户id
final User user = mapper.selectById(1l);
// 修改用户信息
user.setName("sama");
user.setEmail("3130272974@qq.com");
// 执行更新操作
final int res = mapper.updateById(user);
System.out.println(res);
}
更新了version
/*
* 乐观锁:失败
* */
@Test
public void test04() {
// 线程1
User user1 = mapper.selectById(1l);
// 修改用户信息
user1.setName("sama-1");
user1.setEmail("3130272974@qq.com");
// 模拟插队线程抢先修改值
User user2 = mapper.selectById(1l);
user1.setName("sama-2");
user1.setEmail("3130272974@qq.com");
final int i = mapper.updateById(user2);
System.out.println(i);
// 执行更新操作
// 解决了这种问题可以采用自旋锁(多次提交尝试)
final int res = mapper.updateById(user1); // 如果没有乐观锁,就会覆盖插队线程的值
System.out.println(res);
}
更新失败,因为version版本发生了变化。
/*
* 查询测试
* */
@Test
public void test05() {
final User user = mapper.selectById(1l);
System.out.println(user);
}
/*
* 批量查询
**/
@Test
public void test06() {
final List<User> users = mapper.selectBatchIds(Arrays.asList(1l, 2l, 3l));
users.foreach(System.out::println);
}
/*
* 条件查询 map
* */
@Test
public void test07() {
final HashMap<String, Object> map = new HashMap<>();
// 自定义查询条件
map.put("name", "sama");
final List<User> users = mapper.selectByMap(map);
users.forEach(System.out::println);
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/f9fe69735203441fb877ab3ac3f1bbb3.png#pic_center)
分页在网站使用的十分多!
如何使用?
/*
* 注册分页插件
* */
@Bean
public paginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
/*
* 测试分页插件
* */
@Test
public void test08() {
final Page<User> page = new Page<>(1, 5);
mapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
}
@H_554_3043@
paget的total方法可以获得记录的总数
/*
* 测试删除
* */
@Test
public void test09() {
final int res = mapper.deleteById(1450089611366764545l);
System.out.println(res);
}
/*
* 批量删除
* */
@Test
public void test10() {
// 通过id批量删除
mapper.deleteBatchIds(Arrays.asList(1l, 2l, 3l));
}
/*
* 通过map删除
* */
@Test
public void test11() {
final HashMap<String, Object> map = new HashMap<>();
map.put("name", "kuku-sama-k");
final int res = mapper.deleteByMap(map);
System.out.println(res);
}
物理删除:从数据中直接移除
逻辑删除:在数据库中没有被移除,而是通过变量让他失效
管理员可以查看被删除的记录,防止重要数据丢失,类似于回收站!
/*
* 逻辑删除
* */
@TableLogic
private Integer deleted;
/*
* 逻辑删除组件
* */
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1 # 逻辑删除
logic-not-delete-value: 0 # 逻辑未删除
值依旧在数据库,但是deleted已经改变了,此时查询也无法查到1号了,会自动过滤被删除的数据
平时的开发过程中,会遇到一些慢sql.通过测试,druid等去查找
MP也听过性能分析插件,如果超过这个时间就停止运行
/*
* sql效率插件
* */
@Bean
@Profile({"dev", "test"}) // 仅在开发和测试环境下进行
public PerformanceInterceptor performanceInterceptor() {
final PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000); // 设置时间
performanceInterceptor.setFormat(true); // 格式化
return performanceInterceptor;
}
# 配置当前环境为dev or test
spring:
profiles:
active: dev
这个东西十分重要,我们写一些复杂的sql,就需要借助这个东西来实现!
测试wrapper使用
@Test
public void test01() {
// 查询name和邮箱不为空的用户.
final QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// 添加条件
queryWrapper
.isNotNull("name")
.isNotNull("email")
.ge("age", 12);
final List<User> list = userMapper.selectList(queryWrapper); // 类似于map映射
list.forEach(System.out::println);
}
@Test
public void test02() {
// 查询名字为sama的用户
final QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "sama");
final User user = userMapper.selectOne(wrapper); // 查询一个结果,多个结果使用list或者map
System.out.println(user);
}
sama已经被逻辑删除了,所以未查询到
@Test
public void test03() {
// 查询年龄在20-30之间的人的总数
final QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age", 20, 30);
final Integer integer = userMapper.selectCount(wrapper); // 查询结果数
System.out.println(integer);
}
@Test
public void test04() {
// 查询名字中不含a的,邮箱以t开头的
final QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左: %t 右:t%
wrapper.notLike("name", "a").likeRight("email", "t");
final List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
public void test05() {
// 嵌套查询
final QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id", "select id From user where id<4");
final List<Object> list = userMapper.selectObjs(wrapper);
list.forEach(System.out::println);
}
@Test
public void test06() {
// 排序
final QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("id"); // id降序
final List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
其余的测试不再一一展示,根据官网查看即可
dao,pojo,service,controller都去自动生成!
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
模板
package edu;
import com.baomidou.mybatisplus.annotation.DBType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Arrays;
/*
* 代码自动生成器
* */
public class KuQuanCode {
public static void main(String[] args) {
final AutoGenerator mpg = new AutoGenerator();
/*
* 配置全局策略
* */
GlobalConfig gc = new GlobalConfig();
// 获取当前项目路径
final String path = System.getProperty("user.dir");
// 设置生成路径
gc.setOutputDir(path + "/src/main/java");
// 设置作者
gc.setAuthor("kuangshen-kuquan");
// 是否覆盖原来生成的代码
gc.setFileOverride(false);
// 设置服务的名字,去service的i前缀
gc.setServiceName("%sService");
// 主键策略-雪花算法
gc.setIdType(IdType.ID_WORKER);
// 配置日期类型
gc.setDateType(DateType.ONLY_DATE);
// 自动配置swagger
gc.setSwagger2(true);
// 将全局配置放入自动生成器
mpg.setGlobalConfig(gc);
/*
* 设置数据源配置
* */
final DataSourceConfig dsc = new DataSourceConfig();
// 设置url
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8");
// 设置驱动名称
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
// 设置用户名
dsc.setUsername("root");
// 设置密码
dsc.setPassword("123");
// 设置数据库类型
dsc.setDbType(DbType.MYSQL);
// 将数据源配置放入自动生成器
mpg.setDataSource(dsc);
/*
* 设置包配置
* */
final PackageConfig pc = new PackageConfig();
// 设置模块名字
pc.setModuleName("test-execute");
// 设置父包
pc.setParent("end");
// 设置实体类的包名字
pc.setEntity("pojo");
// 设置mapper的包名
pc.setMapper("mapper");
// 设置service的包名
pc.setService("service");
// 设置controller的包名
pc.setController("controller");
// 将包配置放入自动生成器
mpg.setPackageInfo(pc);
/*
* 策略配置
* */
StrategyConfig strategy = new StrategyConfig();
// 设置映射的表名 重点-每次只需要修改这里的值就好了
strategy.setInclude("user");
// 表名中下划线转驼峰
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名下划线转驼峰
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 设置父类
/*strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");*/
// 自动使用lombok
strategy.setEntityLombokModel(true);
// 逻辑删除
strategy.setLogicDeleteFieldName("deleted");
// 自动填充策略配置
final TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
final TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
strategy.setTableFillList(Arrays.asList(createTime, updateTime));
// 乐观锁配置
strategy.setVersionFieldName("version");
// 驼峰命名
strategy.setRestControllerStyle(true);
// 设置请求链接 例如:localhost:8080/hello_id_2
strategy.setControllerMappingHyphenStyle(true);
// 将策略配置放入自动生成器中
mpg.setStrategy(strategy);
// 执行
mpg.execute();
}
}
可以使用这个直接生成大量代码,极大的简化开发流程,提升开发速度
生成的代码(从视频中截取)
以上是脚本宝典为你收集整理的狂神说MybatisPlus全部内容,希望文章能够帮你解决狂神说MybatisPlus所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。