mybatis-plus
概述
MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特点
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
使用Mp
<!--注意!:mybatis无法同mybatisPlus包同存(Plus包含原版)--> <properties> <!--java使用版本--> <java.version>8</java.version> </properties> <dependencies> <!--web依赖jar--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--单元测试jar--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--引入swagger2依赖--> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.1.RELEASE</version> </dependency> <!--图形化依赖--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> <!--myBatisPlus包--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.7</version> </dependency> <!--mysql的驱动依赖 3.--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>配置文件(application.properties)
spring.application.name=qy174-springboot-mp #数据库 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root #映射文件路径 mybatis-plus.mapper-locations=classpath*:mapper/*.xml #配置日志--sql日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl实体类
//实体类 @Data @TableName(value = "name")//表名不一致注释 public class User { @TableId//声明主键 private Integer id; @TableField(value = "user_name")//l名不一致注释 private String name; }mapper文件
//声明实例不报红 @Repository //继承BaseMapper<实体类名> public interface DeptMapper extends BaseMapper<Dept> { //使用联表分页查询 IPage<实体类名> selectByPage(IPage<实体类名> page, @Param("em") Wrapper<实体类名> queryWrapper); }声明mapper文件(...Application.java)
@SpringBootApplication //将指定包内声明为mapper文件 @MapperScan(basePackages = {"com.gzx.demo3homework.mapper"}) public class Demo3HomeWorkApplication { public static void main(String[] args) { SpringApplication.run(Demo3HomeWorkApplication.class, args); } }分页插件(config/MybatisPlusConfig.java)
@Configuration public class MybatisPlusConfig { /** * 添加分页插件 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
实例
//实体类 @Data @TableName(value = "name")//表名不一致注释 public class User { @TableId//声明主键 @TableField(value = "Id")//l名不一致注释 private Integer id; private String name; } //mapper @Repository//使其他类声明mapper类对象无错误 public interface UserMapper extends BaseMapper<User> { } @SpringBootApplication //mapper生成代理实现类 @MapperScan("com.gzx.demo1.mapper") public class Demo1Application { public static void main(String[] args) { SpringApplication.run(Demo1Application.class, args); } }//根据id查询 @SpringBootTest class Qy174SpringbootMpApplicationTests { @Autowired private UserMapper userMapper; /** * 如果出现实体类和表名不一致。@TableName * 如果出现实体类属性名和字段名不一致。@TableField */ @Test void testSelectById() { User user = userMapper.selectById(1); System.out.println(user); } @Test void testInsert(){ //添加一条记录 User user=new User(null,"aaa",19,"123@qq.com"); //添加--把生成的主键也会赋值给对象中主键属性 System.out.println("填进去:"+user); int row = userMapper.insert(user); System.out.println(row); System.out.println("填进去后:"+user); //批量添加 List<User> list=new ArrayList<>(); list.add(new User(null,"bbb",18,"123@qq.com")); list.add(new User(null,"ccc",19,"223@qq.com")); list.add(new User(null,"ddd",19,"323@qq.com")); list.add(new User(null,"eee",17,"323@qq.com")); List<BatchResult> insert = userMapper.insert(list); //如果有id则修改 没有则添加 User user=new User(2,"aaa",19,"123@qq.com"); userMapper.insertOrUpdate(user); } }
批量删除
@Test public void testDelete(){ //根据主键删除 // int i = userMapper.deleteById(1); // System.out.println(i); //批量删除 // int i = userMapper.deleteByIds(Arrays.asList(1, 2, 3)); // System.out.println(i); //根据条件删除 // Wrapper:条件类对象. 每个条件被封装成对应的方法 UpdateWrapper<User> wrapper=new UpdateWrapper<>(); // wrapper.like("uname","刘"); //小于 // wrapper.le("age",19); // wrapper.in("uname","jone","Tom"); // wrapper.ne("age",19); // wrapper.between("age",19,35); wrapper.like("uname","六").or().gt("age",19); userMapper.delete(wrapper); }
批量修改
@Test public void testUpdate(){ //根据主键更新一条数据 // User user=new User(1,"刘帅鹏",19,"123@qq.com"); // int i = userMapper.updateById(user); // System.out.println(i); //批量更新 // List<User> users=new ArrayList<>(); // Collections.addAll(users, // new User(1,"张学友",19,"118"), // new User(2,"闫克起",17,"120"), // new User(3,"刘德华",110,"130")); // userMapper.updateById(users); //根据其他条件更新 User user=new User(); user.setAge(110); userMapper.update(user,new UpdateWrapper<User>().eq("uname","刘德华")); }
批量查询
@Test public void testSelect(){ UserVo userVo =new UserVo(); userVo.setName("李"); userVo.setMin(9); QueryWrapper<User> wrapper=new QueryWrapper<>(); //指定查询的列 if(StringUtils.isNotBlank(userVo.getName())){ wrapper.like("uname",userVo.getName()); } if(userVo.getMin()!=null){ wrapper.ge("age",userVo.getMin()); } if(Objects.nonNull(userVo.getMax())){ wrapper.le("age",userVo.getMax()); } List<User> users = userMapper.selectList(wrapper); users.stream().forEach(System.out::println); }
分页查询
//使用mp的分页拦截器 @Test public void testSelectPage(){ //分页对象 Page<User> page=new Page<>(2,2); //查询条件对象 Page<User> userPage = userMapper.selectPage(page, null); System.out.println("总页数:"+userPage.getPages()); System.out.println("当前页的记录:"+userPage.getRecords()); System.out.println("总条数:"+userPage.getTotal()); } @Configuration public class MybatisPlusConfig { /** * 添加分页插件 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
连表分页条件查询
@Repository public interface EmpMapper extends BaseMapper<Emp> { IPage<Emp> selectByPage(IPage<Emp> page, @Param("em") Wrapper<Emp> queryWrapper); }映射文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.qy174springbootmp.mapper.UserMapper"> <resultMap id="BaseMapping" type="com.example.qy174springbootmp.entity.User"> <id property="id" column="id" javaType="java.lang.Integer"/> <result property="name" column="uname" javaType="java.lang.String"/> <result property="age" column="age" javaType="java.lang.Integer"/> <result property="email" column="email" javaType="java.lang.String"/> <!--多对一的标签--> <association property="clazz" javaType="com.example.qy174springbootmp.entity.Clazz"> <id property="cid" column="cid" javaType="java.lang.Integer"/> <result property="cname" column="cname" javaType="java.lang.String"/> </association> </resultMap> <select id="selectByPage" resultMap="BaseMapping"> select * from tbl_user u join tbl_clazz c on u.class_id=c.cid ${ew.customSqlSegment} </select> </mapper>测试
@Test public void testSelectByPage(){ Page<User> page=new Page<>(1,2); QueryWrapper<User> wrapper=new QueryWrapper<>(); // wrapper.like("uname","张"); IPage<User> userPage = userMapper.selectByPage(page, wrapper); System.out.println("总页数:"+userPage.getPages()); System.out.println("当前页的记录:"+userPage.getRecords()); System.out.println("总条数:"+userPage.getTotal()); }