MyBatis-Plus

  •  简介
    • Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。
    • https://mp.baomidou.com/guide/config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
  • 特性

    • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
      损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
      强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操
      作,更有强大的条件构造器,满足各类使用需求
      支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
      支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、       SQLServer 等多种数据库
      支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美
      解决主键问题
      支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
      支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD
      操作
      支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
      支持关键词自动转义:支持数据库关键词(order、key......)自动转义,还可自定义关键词
      内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代
      码,支持模板引擎,更有超多自定义配置等您来使用
      内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通
      List 查询
      内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
      内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
      内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

  • 初始数据库:

    • CREATE TABLE `user` (
      `id` bigint(20) NOT NULL COMMENT '主键ID', 
      `name` varchar(30) DEFAULT NULL COMMENT '姓名', 
      `age` int(11) DEFAULT NULL COMMENT '年龄', 
      `email` varchar(50) DEFAULT NULL COMMENT '邮箱', 
      PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
      -- 插入数据 
      INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('1', 'Jone', '18', '[email protected]'); 
      INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('2', 'Jack', '20', '[email protected]'); 
      INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('3', 'Tom', '28', '[email protected]'); 
      INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('4', 'Sandy', '21', '[email protected]');
      INSERT INTO `user` (`id`, `name`, `age`, `email`) VALUES ('5', 'Billie', '24', '[email protected]');

       

  • pom

    • 
      
          4.0.0
      
          
              org.springframework.boot
              spring-boot-starter-parent
              2.1.0.RELEASE
          
      
          mybatisplus
          mybatis-plus
          1.0-SNAPSHOT
      
          
              
                  org.springframework.boot
                  spring-boot-starter
              
              
                  org.springframework.boot
                  spring-boot-starter-test
                  test
              
              
              
                  com.baomidou
                  mybatis-plus-boot-starter
                  3.0.5
              
              
              
                  mysql
                  mysql-connector-java
                  5.1.47
              
              
              
                  org.projectlombok
                  lombok
                  true
                  1.18.4
              
          
          
              
                  
                      org.springframework.boot
                      spring-boot-maven-plugin
                  
              
          
      

       

  • log4j.xml

    • 
      
      
          
              
              
                  
              
          
          
              
          
          
              
          
          
              
              
          
      

       

  • jdbc.properties

    • jdbc.driver=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql:///数据库名?useUnicode=true&characterEncoding=utf8
      jdbc.username=#
      jdbc.password=#

       

  • mybatis-config.xml

    • 因为是与spring整合,所有mybatis-plus的大部分都写在spring的配置文件中,这里定义一个空的mybatis-config.xml即可

    • 
      
      
      
  • BaseMapper

    • MybatisPlus中,BaseMapper中定义了一些常用的CRUD方法,当我们自定义的Mapper接口继承BaseMapper后即可拥有了这些方法。

    • import com.baomidou.mybatisplus.core.conditions.Wrapper;
      import com.baomidou.mybatisplus.core.metadata.IPage;
      import com.baomidou.mybatisplus.core.toolkit.Constants;
      import org.apache.ibatis.annotations.Param;
      
      import java.io.Serializable;
      import java.util.Collection;
      import java.util.List;
      
      /*** 

      * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能 *

      *

      * 这个 Mapper 支持 id 泛型 *

      ** @author hubin * @since 2016-01-23 */ public interface BaseMapper { /***

      * 插入一条记录 *

      ** @param entity 实体对象 */ int insert(T entity); /***

      * 根据 ID 删除 *

      ** @param id 主键ID */ int deleteById(Serializable id); /***

      * 根据 columnMap 条件,删除记录 *

      ** @param columnMap 表字段 map 对象 */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap); /***

      * 根据 entity 条件,删除记录 *

      ** @param queryWrapper 实体对象封装操作类(可以为 null) */ int delete(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 删除(根据ID 批量删除) *

      ** @param idList 主键ID列表(不能为 null 以及 empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection idList); /***

      * 根据 ID 修改 *

      ** @param entity 实体对象 */ int updateById(@Param(Constants.ENTITY) T entity); /***

      * 根据 whereEntity 条件,更新记录 *

      ** @param entity 实体对象 (set 条件值,不能为 null) * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)*/ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper); /***

      * 根据 ID 查询 *

      ** @param id 主键ID */ T selectById(Serializable id); /***

      * 查询(根据ID 批量查询) *

      ** @param idList 主键ID列表(不能为 null 以及 empty) */ List selectBatchIds(@Param(Constants.COLLECTION) Collection idList); /***

      * 查询(根据 columnMap 条件) *

      ** @param columnMap 表字段 map 对象 */ List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap); /***

      * 根据 entity 条件,查询一条记录 *

      ** @param queryWrapper 实体对象 */ T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 Wrapper 条件,查询总记录数 *

      ** @param queryWrapper 实体对象 */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 entity 条件,查询全部记录 *

      ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 Wrapper 条件,查询全部记录 *

      ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 Wrapper 条件,查询全部记录 * 注意: 只返回第一个字段的值 *

      ** @param queryWrapper 实体对象封装操作类(可以为 null) */ List selectObjs(@Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 entity 条件,查询全部记录(并翻页)*

      ** @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) */ IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper); /***

      * 根据 Wrapper 条件,查询全部记录(并翻页) *

      ** @param page 分页查询条件 * @param queryWrapper 实体对象封装操作类 */ IPage> selectMapsPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper); }

       

    • 实体类注解:

      • @Data
        @TableName(value = "tb_employee")//指定表名
        public class User{
            //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
            @TableId(value = "id",type = IdType.AUTO)//指定自增策略
            private Integer id;
            //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
            //@TableField(value = "last_name",exist = true)
            //private String lastName;
            private String name;
            private Integer age;
            private String email;
        }

         

    • interface

      • public interface UserMapper extends BaseMapper {
        
        }
        

         

    • 分页查询: 记得在启动类上加@MapperScan 注解, 指定扫描的包

      •     /**
             * 分页插件
             */
            @Bean
            public PaginationInterceptor paginationInterceptor() {
                return new PaginationInterceptor();
            }

         

    • 配置

      • 虽然在MybatisPlus中可以实现零配置,但是有些时候需要我们自定义一些配置,就需要使用Mybatis原生的一些配置文件方式了。
        • # 指定全局配置文件 
          mybatis-plus.config-location = classpath:mybatis-config.xml 
          # 指定mapper.xml文件 
          mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
    • 测试案例:
      • 
        import cn.itcast.mybatisplus.pojo.User;
        import com.baomidou.mybatisplus.core.conditions.Wrapper;
        import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
        import com.baomidou.mybatisplus.core.metadata.IPage;
        import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
        import org.junit.Test;
        import org.junit.runner.RunWith;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;
        import org.springframework.test.context.junit4.SpringRunner;
        
        import java.util.List;
        
        @RunWith(SpringRunner.class)
        @SpringBootTest
        public class UserMaperTest {
        
            @Autowired
            private UserMapper userMapper;
        
            @Test
            public void testSelect(){
                List users = this.userMapper.selectList(null);
                for (User user : users) {
                    System.out.println(user);
                }
            }
        
            @Test
            public void testSelectById(){
                User user = this.userMapper.selectById(3L);
                System.out.println(user);
            }
        
            @Test
            public void testSelectByLike(){
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.like("name", "o");
                List list = this.userMapper.selectList(wrapper);
                for (User user : list) {
                    System.out.println(user);
                }
            }
        
            @Test
            public void testSelectByLe(){
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.le("age", 20);
                List list = this.userMapper.selectList(wrapper);
                for (User user : list) {
                    System.out.println(user);
                }
            }
        
            @Test
            public void testSave(){
                User user = new User();
                user.setAge(25);
                user.setEmail("[email protected]");
                user.setName("zhangsan");
                int count = this.userMapper.insert(user);
                System.out.println("新增数据成功! count => " + count);
            }
        
            @Test
            public void testDelete(){
                this.userMapper.deleteById(7L);
                System.out.println("删除成功!");
            }
        
            @Test
            public void testUpdate(){
                User user = new User();
                user.setId(6L);
                user.setName("lisi");
                this.userMapper.updateById(user);
                System.out.println("修改成功!");
            }
        
            @Test
            public void testSelectPage() {
                Page page = new Page<>(2, 2);
                IPage userIPage = this.userMapper.selectPage(page, null);
                System.out.println("总条数 ------> " + userIPage.getTotal());
                System.out.println("当前页数 ------> " + userIPage.getCurrent());
                System.out.println("当前每页显示数 ------> " + userIPage.getSize());
                List records = userIPage.getRecords();
                for (User user : records) {
                    System.out.println(user);
                }
            }
        
        }
    • 使用MybatisPlusAutoGenerator插件生成代码文件

      • 编写BasePojo文件

        • 抽取公共的字段  根据自己的业务来抽取. 如果没有的话, 也可以不加

          • import lombok.Data;
            
            import java.util.Date;
            
            @Data
            public abstract class BasePojo implements java.io.Serializable {
                private Date created;
                private Date updated;
            }

             

      • 增加模版依赖

        •  
               
               
                  org.freemarker 
                  freemarker 
                  2.3.28 
               
           

           

      • 编写CodeGenerator

        • 参照官方文档案例改一下就ok了.

        • https://mp.baomidou.com/guide/generator.html

          • 注意:

            • 文档上写的目录 user.dir 是项目的根目录.

          • @EqualsAndHashCode(callSuper = true)

            这个是自动生成equalshashCode方法,我们一般不需要,所以将该注解去掉

          •  

            @Accessors(chain = true)  

            这个是表示,生成的set方法将采用链式编程方式,建议保留。

        • 生成完实体之后,记得写指定 表名和主键id的注解.

        • 注意int类型和布尔类型的值 是否正确. 数据库的int容易翻译成Boolean

    • 你可能感兴趣的:(springboot,mysql,后端)