mybatis-plus的使用总结

一:什么是 MyBatis-Plus?

MyBatis-Plus 是 MyBatis 的一个强大的增强工具包,用于简化开发。该工具包为 MyBatis 提供了一些高效、有用、开箱即用的功能,使用它可以有效地节省您的开发时间。
企业版 Mybatis-Mate 高级特性

特征

  • 完全兼容 MyBatis
  • 启动时自动配置
  • 开箱即用的数据库操作界面
  • 强大而灵活的 where 条件包装器
  • 生成主键的多种策略
  • Lambda 风格的 API
  • 全能且高度可定制的代码生成器
  • 自动分页操作
  • SQL注入防御
  • 支持主动记录
  • 支持可插拔的自定义接口
  • 内置许多有用的扩展

Getting started

  • Maven:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>Latest Version</version>
</dependency>
  • Gradle
compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: 'Latest Version'

代码自动生成器


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * Oracle数据库
 * mybatis-plus代码生成器(用于生成entity)<br>
 * @author Administrator
 */
public class MyBatisPlusGenerator {

    public static void main(String[] args) {
        //模块名
        String moduleName="equipment-server";
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath+"/"+moduleName);
        gc.setOutputDir(projectPath+"/"+moduleName + "/src/main/java");
        gc.setFileOverride(true);// 是否覆盖
        gc.setActiveRecord(true);

//        gc.setIdType(IdType.ASSIGN_ID); //主键策略
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        gc.setAuthor("yin");
        gc.setSwagger2(true);

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.ORACLE);
        dsc.setTypeConvert(new OracleTypeConvert());

        //配置数据源
        dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
        dsc.setUsername("testDb");
        dsc.setPassword("123456");
        dsc.setUrl("jdbc:oracle:thin:@192.168.0.120:1521/orcl");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
//        strategy.setTablePrefix(new String[]{"SYS_"});// 此处修改为表前缀
        strategy.setInclude(new String[]{"SF_CHARGE_CONFIRMATION_ORDER"});//设置要映射的表名
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符



        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(moduleName);
        pc.setParent("cn.gewut.business.core.plus");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setXml("mapper");

        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };


        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
//         String templatePath = "/templates/controller.java.vm";
//
//        // 自定义输出配置
//        List<FileOutConfig> focList = new ArrayList<>();
//        // 自定义配置会被优先输出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
//
//                return "../controller/"+tableInfo.getEntityName()
//                        + StringPool.DOT_JAVA;
//            }
//        });
//        cfg.setFileOutConfigList(focList);


         TemplateConfig tc = new TemplateConfig();
         tc.setController("/templates/controller.java.vm");
         tc.setEntity("/templates/entity.java.vm");
         tc.setMapper("/templates/mapper.java.vm");
         tc.setXml("/templates/mapper.xml.vm");
         tc.setService("/templates/service.java.vm");
         tc.setServiceImpl("/templates/serviceImpl.java.vm");
//         如上任何一个模块如果设置 空 OR Null 将不生成该模块。
         mpg.setTemplate(tc);
        mpg.setCfg(cfg);
        // 执行生成
        mpg.execute();
        // 打印注入设置
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }


}

官方教程

二 :PageHelper使用注意事项

1.PageHelper分页只会作用于第一次查询,对第二次及以后的查询无效

分页插件PageHelper工作原理

MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上进行了简单的封装,提供了许多常用的功能,让开发人员可以更加便捷地使用MyBatis进行数据库操作。 在使用MyBatis-Plus之前,需要先引入MyBatis-Plus的依赖: ```xml <!-- MyBatis-Plus依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> ``` 然后,在Spring Boot的配置文件中添加MyBatis-Plus的配置: ```properties # MyBatis-Plus配置 mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml mybatis-plus.global-config.id-type=auto mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0 ``` 在以上配置中,`mybatis-plus.mapper-locations`指定了Mapper文件的位置,`mybatis-plus.global-config.id-type`指定了主键生成策略,`mybatis-plus.global-config.db-config.logic-delete-value`和`mybatis-plus.global-config.db-config.logic-not-delete-value`指定了逻辑删除的值。 接下来,我们就可以开始使用MyBatis-Plus了。 ## 增 使用MyBatis-Plus进行插入操作,可以使用`insert`方法: ```java User user = new User(); user.setName("张三"); user.setAge(20); userMapper.insert(user); ``` 在以上代码中,我们创建了一个`User`对象,并设置了`name`和`age`属性,然后调用了`userMapper.insert(user)`方法进行插入操作。 ## 删 使用MyBatis-Plus进行删除操作,可以使用`deleteById`方法: ```java userMapper.deleteById(1L); ``` 在以上代码中,我们调用了`userMapper.deleteById(1L)`方法进行删除操作,其中的`1L`表示要删除的记录的主键。 ## 改 使用MyBatis-Plus进行更新操作,可以使用`updateById`方法: ```java User user = new User(); user.setId(1L); user.setName("李四"); user.setAge(25); userMapper.updateById(user); ``` 在以上代码中,我们创建了一个`User`对象,并设置了`id`、`name`和`age`属性,然后调用了`userMapper.updateById(user)`方法进行更新操作。 ## 查 使用MyBatis-Plus进行查询操作,可以使用`selectById`方法: ```java User user = userMapper.selectById(1L); ``` 在以上代码中,我们调用了`userMapper.selectById(1L)`方法进行查询操作,其中的`1L`表示要查询的记录的主键,查询结果会返回一个`User`对象。 除了`selectById`方法,MyBatis-Plus还提供了许多其他的查询方法,例如`selectList`、`selectPage`等,可以根据具体的需求进行选择。 ## 总结 以上就是MyBatis-Plus的基本使用教程,通过使用MyBatis-Plus,我们可以更加便捷地进行数据库操作,提高开发效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值