zoukankan      html  css  js  c++  java
  • Mybatis-plus

    不做 curd Boy ,为偷懒而生



    1. Mybatis-plus

    MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生


    MP 有很多强大的功能,但笔者常用的还是下面三种:

    • 强大的 CRUD 操作
    • 内置代码生成器
    • 内置分页插件






    2. Hello World

    笔者跟着 官方文档 走了一遍,是中文文档!!!



    2.1 创建数据库

    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)
    );
    
    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.2 导入依赖

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3.1</version>
    </dependency>
    
    <!--  非必要  -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    

    引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题



    2.3 配置

    server:
      port: 8080
    
    spring:
      application:
        name: mybatis-plus-test
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&CharacterEncoding=utf-8
        username: xxxx
        password: xxxx
    


    2.4 编写代码

    // entity实体类
    // 实现序列化接口,MP传递参数
    @Data
    public class User implements Serializable {
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    

    // mapper接口类,继承了MP的BaseMapper
    // 这里要注意:记得写泛型
    @Repository
    public interface UserMapper extends BaseMapper<User> {
    }
    

    // 包扫描
    // 也可写个配置了,在配置类上包扫描
    @SpringBootApplication
    @MapperScan("com.howl.mapper")
    public class MybatisPlusApplication {
        public static void main(String[] args) {
            SpringApplication.run(MybatisPlusApplication.class, args);
        }
    }
    


    2.5 测试

    @SpringBootTest
    class MybatisPlusApplicationTests {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void testSelect() {
            List<User> userList = userMapper.selectList(null);
            userList.forEach(System.out::println);		
        }
    }
    






    3. 常见的方法

    我们继承 MP 的 BaseMapper 或 IService 接口即可,然后就可使用 MP 内置常见的 CURD 方法。下面方法的 Page 和 Wrapper 后面会说明



    3.1 BaseMapper

    方法 说明
    selectById(Serializable id)
    selectBatchIds(Collection<? extends Serializable> idList) 批量操作
    selectOne(Wrapper queryWrapper)
    selectCount(Wrapper queryWrapper)
    selectList(Wrapper queryWrapper)
    selectPage(P page, Wrapper queryWrapper)
    updateById(T entity)
    update(T entity, Wrapper updateWrapper)
    insert(T entity)
    deleteById(Serializable id);
    delete(Wrapper queryWrapper)
    deleteBatchIds(Collection<? extends Serializable> idList)


    3.2 IService

    在 BaseMapper 的基础上添加几个方法即可,重复的不展示了

    方法 说明
    saveOrUpdate(T entity) 根据 @TableId 判断
    saveOrUpdate(T entity, Wrapper updateWrapper) 根据 Wrapper 来判断
    saveOrUpdateBatch(Collection entityList) 批量操作






    4. 常见的注解

    笔者使用这个来代替 ResultMap 的,此外还有一些其他用法


    • @TableName:表名注解
    • @TableId:主键注解
    • @TableFiled:字段注解(非主键)
    • @Version:乐观锁注解
    • @TableLogic:逻辑删除注解
    • @OrderBy:内置 SQL 默认指定排序,优先级低于 wrapper 条件查询






    5. 分页查询

    分页本质就是帮你修改 SQL 语句,那么就是通过拦截器来截取你的 SQL 语句然后修改再发送给数据库执行



    5.1 配置拦截器组件

    @Configuration
    public class MybatisPlusConfig {
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
    }
    


    5.2 使用 Page 对象

    @Test
    public void testSelectPage() {
        Page<User> page = new Page<>(2,2);				// 当curPage、pageSize
        userMapper.selectPage(page, null);
        page.getRecords().forEach(System.out::println);
    }
    


    5.3 Page对象

    public class Page<T> implements IPage<T> {
        private static final long serialVersionUID = 8545996863226528798L;
        protected List<T> records;
        protected long total;
        protected long size;
        protected long current;
        protected List<OrderItem> orders;
        protected boolean optimizeCountSql;
        protected boolean searchCount;
        protected String countId;
        protected Long maxLimit;
    }
    






    6. 条件构造器

    一些复杂的 SQL 语句用 Wapper 会显得特别简单,本质就是将特殊 SQL 语句用面向对象的方式解决


    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    
    queryWrapper.ge("age", 20)
        .eq("age", 20)
        .ne("age", 20)
        .le("age", 20);
    
    
    queryWrapper.between("age", 20, 30)
        .in("age", 1);
    
    
    queryWrapper.like("name", "Howl")
        .notLike("name", "let")
        .likeLeft("name", "Ho")
        .likeRight("name", "wl");
    
    
    queryWrapper.orderByAsc("age")
        .orderByDesc("age")
        .groupBy("age");
    






    7. 填充操作


    7.1 删除建表时设置的默认值

    在数据库中删除 default 值



    7.2 实体类字段上添加注解

    @Data
    public class User {
    
        private Long id;
        private String name;
        private Integer age;
        private String email;
    
        @TableField(fill = FieldFill.INSERT)
        private Date createTime;
        @TableField(fill = FieldFill.INSERT_UPDATE)
        private Date updateTime;
    }
    


    7.3 编写处理器

    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
    






    8. 代码生成器

    AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。


    8.1 添加依赖

    generator、velocity在新版本中被移除了

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.1</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.3</version>
    </dependency>
    


    8.2 写配置

    public class CodeGenerator {
        public static void main(String[] args) {
    
            // 代码自动生成器
            AutoGenerator autoGenerator = new AutoGenerator();
    
            // 全局配置,generator包下的
            GlobalConfig globalConfig = new GlobalConfig()
                    .setOutputDir(System.getProperty("user.dir") + "/src/main/java")
                    .setAuthor("Howl")
                	.setServiceName("%sService")
                    .setOpen(false)
                    .setFileOverride(false);		// 重写覆盖
    
            // 数据源配置
            DataSourceConfig dataSourceConfig = new DataSourceConfig()
                    .setUrl("jdbc:mysql://1.116.136.137:3306/user")
                    .setDriverName("com.mysql.jdbc.Driver")
                    .setUsername("root")
                    .setPassword("110110110");
    
            // 包配置
            PackageConfig packageConfig = new PackageConfig()
    				// .setModuleName("mp")     多一个包层次,然后Controller映射地址上也会多一个 /mp
                    .setParent("com.howl");
    
            // 策略配置
            StrategyConfig strategyConfig = new StrategyConfig()
                    // .setInclude("user","")			不写全部表都创建进来
                    .setNaming(NamingStrategy.underline_to_camel)
                    .setColumnNaming(NamingStrategy.underline_to_camel)
                    .setEntityLombokModel(true)
                    .setRestControllerStyle(true)
                    .setControllerMappingHyphenStyle(true);		// 地址映射支持下划线,非驼峰
    
            // 生成器设置以上配置
            autoGenerator.setGlobalConfig(globalConfig)
                    .setDataSource(dataSourceConfig)
                    .setPackageInfo(packageConfig)
                    .setStrategy(strategyConfig);
    
            // 执行生成代码
            autoGenerator.execute();
        }
    }
    






    9. 补充

    笔者以前看见日志就怕,现在报错就老是找日志了,Mybatis 支持多种日志配置,这里使用了标准输出

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  • 相关阅读:
    Unity 用代码设置UGUI的渲染层级
    C/C++常考基础面试题(更新)
    运行Jar包程序Shell
    Shell编程语法
    Spring多个数据源问题:DataSourceAutoConfiguration required a single bean, but * were found
    Maven项目的发布,发布到Nexus
    Consul入门
    application.properties 改成 application.yml
    奖学金申请模板
    jvm
  • 原文地址:https://www.cnblogs.com/Howlet/p/15116674.html
Copyright © 2011-2022 走看看