学习springBoot+mybatis-plus+oracle集成

2022-07-29 11:49:38

springBoot集成mybatis-plus

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

1.特点

  • 无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变
  • 预防Sql注入:内置 Sql 注入剥离器,有效预防Sql注入攻击
  • 通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码
  • 内置分页插件:基于 Mybatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作

2.依赖

<!--  oracle --><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>11.1.0.7.0</version></dependency><!-- mybatis --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0-gamma</version></dependency>

oracle连接jar在中央仓库没用,需要自己下载后手动安装到本地仓库,语法:mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.1.0.7.0 -Dpackaging=jar -Dfile=ojdbc6.11.1.0.7.0.jar

3.使用插件生成控制器,实体,服务,xml文件等等

插件默认使用volecity生成,可以自己设置模板引擎,模板文件可以从插件jar包的templates目录拷贝修改。

     AutoGenerator mpg =new AutoGenerator();// 选择 freemarker 引擎,默认 Veloctiy// mpg.setTemplateEngine(new FreemarkerTemplateEngine());// 全局配置
        GlobalConfig gc =new GlobalConfig();
        gc.setOutputDir("F:\\");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList// .setKotlin(true) 是否生成 kotlin 代码
        gc.setAuthor("xxx");// 自定义文件命名,注意 %s 会自动填充表实体属性!// gc.setMapperName("%sDao");// gc.setXmlName("%sDao");// gc.setServiceName("MP%sService");// gc.setServiceImplName("%sServiceDiy");// gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);// 数据源配置
        DataSourceConfig dsc =new DataSourceConfig();
        dsc.setDbType(DbType.ORACLE);
        dsc.setTypeConvert(new OracleTypeConvert());
        dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
        dsc.setUsername("xxx");
        dsc.setPassword("xxx");
        dsc.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
        mpg.setDataSource(dsc);// 策略配置
        StrategyConfig strategy =new StrategyConfig();// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意//        strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(tables);// 需要生成的表// strategy.setExclude(new String[]{"test"}); // 排除生成的表// 自定义实体父类// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");// 自定义实体,公共字段// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });// 自定义 mapper 父类// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");// 自定义 service 父类// strategy.setSuperServiceClass("com.baomidou.demo.TestService");// 自定义 service 实现类父类// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");// 自定义 controller 父类// strategy.setSuperControllerClass("com.baomidou.demo.TestController");// 【实体】是否生成字段常量(默认 false)// public static final String ID = "test_id";// strategy.setEntityColumnConstant(true);// 【实体】是否为构建者模型(默认 false)// public User setName(String name) {this.name = name; return this;}// strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);// 包配置
        PackageConfig pc =new PackageConfig();
        pc.setParent("com.lg.iboot");
        pc.setModuleName("note");
        mpg.setPackageInfo(pc);// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg =new InjectionConfig() {@OverridepublicvoidinitMap() {
                Map<String, Object> map =new HashMap<String, Object>();
                map.put("abc",this.getConfig().getGlobalConfig().getAuthor() +"-mp");this.setMap(map);
            }
        };// 关闭默认 xml 生成,调整生成 至 根目录
        TemplateConfig tc =new TemplateConfig();
        tc.setController("/templates/controller.java.vm");
        tc.setEntity("entity.java.vm");
        tc.setMapper("mapper.java.vm");
        tc.setXml("mapper.xml.vm");
        tc.setService("service.java.vm");
        tc.setServiceImpl("serviceImpl.java.vm");

        mpg.setTemplate(tc);// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称// TemplateConfig tc = new TemplateConfig();// tc.setController("...");// tc.setEntity("...");// tc.setMapper("...");// tc.setXml("...");// tc.setService("...");// tc.setServiceImpl("...");// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。// mpg.setTemplate(tc);// 执行生成
        mpg.execute();

执行完成后会弹出生成的文件

4.application.properties文件配置

#mybatis
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
mybatis-plus.type-aliases-package=com.lg.iboot.*.entity
mybatis-plus.configuration.cache-enabled=false
#如果插件版本是3.0-gamma这个选项必须配置,否则会nullPoint
mybatis-plus.global-config.db-config.db-type=oracle
#配置JdbcTypeForNull, oracle数据库必须配置
mybatis-plus.configuration.jdbc-type-for-null=null

#数据库
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

server.port=8080
server.servlet.context-path=/iboot

5.MybatisConf类配置

@Configuration@MapperScan("com.lg.iboot.note.mapper*")publicclassMybatisConf {@Beanpublic PaginationInterceptorpaginationInterceptor() {returnnew PaginationInterceptor();
    }
}

6.修改controlle类

@Controller@RequestMapping("/note")publicclassNoteController {private Logger logger = LoggerFactory.getLogger(NoteController.class);@Autowiredprivate INoteService noteService;@RequestMapping("/getAll")@ResponseBodypublic ResultgetNotes(){
        logger.info("请求获取note、list");
        Result result =null;try {
            Wrapper<Note> wrapper =null;
            List<Note> notes = noteService.selectList(wrapper);
            result = Result.success(notes);
        }catch (Exception e) {
            e.printStackTrace();
            logger.info("获取notes,出错");
            result = Result.error(-1,"系统异常");
        }return result;
    }
}

7.测试

浏览器输入:http://localhost:8080/iboot/note/getAll
结果如下
这里写图片描述

  • 作者:qw12312312
  • 原文链接:https://blog.csdn.net/qw12312312/article/details/82091952
    更新时间:2022-07-29 11:49:38