Mybatis-plus入门
内容来源于官方文档:mp.baomidou.com/
1:Mybatis-plus是什么?
-
Mybatis-Plus(简称MP)是一个Mybatis的增强工具
-
只是在Mybatis的基础上做了增强却不做改变
-
MyBatis-Plus支持所有Mybatis原生的特性
-
所以引入Mybatis-Plus不会对现有的Mybatis构架产生任何影响
-
MyBatis 增强工具包,简化 CRUD 操作
-
启动加载 XML 配置时注入单表 SQL 操作 ,为简化开发工作、提高生产率而生。
- 最后总结就是为了简化开发 提高效率!
2:Mybatis-plus的特性(官网 :mp.baomidou.com/):
-
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
<!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- lombok驱动 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- mybatis-plus 驱动 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.2</version> </dependency>
3:配置mysql配置文件:
spring.datasource.username=root spring.datasource.password=5825600 spring.datasource.url=jdbc:mysql://localhost:3306/xiaolu?useSSL=false&useUnicode=false&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl # 配置逻辑删除 mybatis-plus.global-config.db-config.logic-delete-value=0 mybatis-plus.global-config.db-config.logic-not-delete-value=1
4:借鉴官网的sql语句来创建表 并插入数据:
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');
5:创建数据库实例:
@Data @NoArgsConstructor @AllArgsConstructor public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; }
6:编写Mapper接口:
//继承BaseMapper类的方法 @Repository //表示持久层 public interface UserMapper extends BaseMapper<User> { }
7:测试类中 测试:
@Autowired UserMapper userMapper; @Test /** * 查询语句 */ void contextLoads() { List<User> users = userMapper.selectList(null); users.forEach(System.out::println);//jdk8的新特性 }
查询结果:

2:根据条件查询:
/* 条件查询用map来设置条件 */ @Test public void selectMap(){ Map<String, Object> map=new HashMap<>(); map.put("name","小杰"); List<User> users = userMapper.selectByMap(map); System.out.println(users); }
3:分页查询:
1:先创建一个配置类来配置分页插件:
//扫描文件件 @MapperScan("com.jie.mapper") @EnableTransactionManagement @Configuration //配置类 public class MyBatisPlusConfig { /** * 这是分页查询的插件 * @return */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; }}
2:在测试类中测试:
/* 分页查询 */ @Test public void selectPage(){ Page<User> page = new Page(1,3); IPage<User> userIPage = userMapper.selectPage(page, null); page.getRecords().forEach(System.out::println); }
众所周知 CRUD:接下来插入语句:
@Test public void insert(){ User user = new User(); user.setName("小杰"); user.setAge(19); user.setEmail("1927545042@qq.com"); /* 因为insert里面要一个参数 这里不写id因为会自动生成id 利用雪花算法: Parameters: 1371685508409307138(Long), 小杰(String), 18(Integer), 1927545042@qq.com(String) 如果像实现id自增的话需要在实体类id上面加注解:@TableId(type = IdType.AUTO) 记得数据库的表也要自增 不然就会报错 */ int insert = userMapper.insert(user); System.out.println(insert); }
实现id自增:(如果像实现id自增的话需要在实体类id上面加注解:@TableId(type = IdType.AUTO)记得数据库的表也要自增 不然就会报错)
@TableId(type = IdType.AUTO) private Long id;
更新语句:
/** * 更新方法 * 所有的sql都是动态sql */ @Test public void update(){ User user = new User(); user.setId(4L); user.setName("小杰"); user.setAge(19); int i = userMapper.updateById(user);//这里面的参数不能填id要填User }
删除语句:
1:根据id删除
@Test public void delect(){ //根据id删除 userMapper.deleteById(1L); }
2:根据条件删除:
@Test public void delect2(){ //根据条件删除 Map map1=new HashMap(); map1.put("name","小杰"); userMapper.deleteByMap(map1); }
3:删除多个数据:
@Test public void delete(){ //删除多个数据 userMapper.deleteBatchIds(Arrays.asList(1371685508409307140L, 1371685508409307141L));
4:逻辑删除:在数据库中没有被移除
1:在数据表中增加deleted字段:![]()
默认值为:1 被删除了的值为:0
2:在配置文件中配置:
# 配置逻辑删除 mybatis-plus.global-config.db-config.logic-delete-value=0 mybatis-plus.global-config.db-config.logic-not-delete-value=1
3:在配置类中添加逻辑删除组件:
@Bean public ISqlInjector sqlInjector(){ return new LogicSqlInjector(); }
4:测试 如果测试成功 数据库的deleted字段的值会显示为0
条件查询(部分) 可以借鉴官网:(mp.baomidou.com/):
1:不为null的值 : isNotNull();
//条件构造器 @Test public void wrapper(){ QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.isNotNull("name");//不为null的值 userMapper.selectList(objectQueryWrapper); }
2:查询一个数据:.eq();
public void test1(){ QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.eq("","");//查询一个数据 多个用map userMapper.selectList(objectQueryWrapper); }
3:查询年龄为10~20的:between();
@Test public void between(){ QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.between("age",10,20); //查询年龄为10——20的; userMapper.selectCount(objectQueryWrapper); }
4:模糊查询 :
notLike:模糊查询
likeLeft :左模糊
likeRight:右模糊
@Test public void test2(){ //模糊查询 QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.notLike("name","小") .likeLeft("age","1") .likeRight("name","k"); //左模糊 和右模糊 % List<Map<String, Object>> maps = userMapper.selectMaps(objectQueryWrapper); maps.forEach(System.out::println); }
5:根据sql语句来进行操作:inSql();
@Test public void sql(){ //条件查询 可以写完整sql语句 QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.inSql("id","select id from user where id=4 "); List<Object> objects = userMapper.selectObjs(objectQueryWrapper); objects.forEach(System.out::println); }
6:升序排序(orderByAsc())和降序排序(orderByDesc()):
@Test public void orb(){ //排序:升序:orderByAsc 降序:orderByDesc() QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>(); objectQueryWrapper.orderByAsc("id"); List<User> users = userMapper.selectList(objectQueryWrapper); users.forEach(System.out::println); }
最后代码自动生成器:可以直接从官网中查找 我这边使用的是狂神的 因为看的狂神的教程:
只需要改实体类名字 和包名 还有 数据库配置即可
/ 代码自动生成器 public class KuangCode { public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("狂神说"); gc.setOpen(false); gc.setFileOverride(false); // 是否覆盖 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/user? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); //只需要改实体类名字 和包名 还有 数据库配置即可 pc.setModuleName("blog"); pc.setParent("com.kuang"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("数据库表的名字可以输入多个"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted"); // 自动填充配置 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //执行 } }
希望大家利用好Mybatis-plus简化开发!!!
如果想看springboot的博客 可以点击我的主页!里面有从入门到外包的一些文章

浙公网安备 33010602011771号