0


SpringBoot(3)整合MyBatis 和MybatisPlus

SpringBoot(3)整合MyBatis 和MybatisPlus

1.整合MyBatis

1.1新建模块

image-20230809133811383

1.2在pom.xml中添加mysql驱动

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency>
1.2.1防止编译时不将静态资源编译进去,在pom.xml中添加
<resources><resource><directory>src/main/resources</directory><includes><include>*.properties</include><include>*.xml</include><include>*.yml</include><include>**/*.xml</include></includes></resource></resources>

1.3.application.yml中添加内容

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

1.2.resources中添加generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEgeneratorConfigurationPUBLIC"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!-- 引入配置文件 --><propertiesresource="jdbc.properties"/><!--指定数据库jdbc驱动jar包的位置--><!--        <classPathEntry location="D:\\developmentTools\\apache-maven-3.6.1\\mvn_resp\\mysql\\mysql-connector-java\\8.0.26\\mysql-connector-java-8.0.26.jar"/>--><!-- 一个数据库一个context --><contextid="infoGuardian"><!-- 注释 --><commentGenerator><propertyname="suppressAllComments"value="true"/><!-- 是否取消注释 --><propertyname="suppressDate"value="true"/><!-- 是否生成注释代时间戳 --></commentGenerator><!-- jdbc连接 --><jdbcConnectiondriverClass="${jdbc.driver}"connectionURL="${jdbc.url}"userId="${jdbc.username}"password="${jdbc.password}"/><!-- 类型转换 --><javaTypeResolver><!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --><propertyname="forceBigDecimals"value="false"/></javaTypeResolver><!-- 01 指定javaBean生成的位置 --><!-- targetPackage:指定生成的model生成所在的包名 --><!-- targetProject:指定在该项目下所在的路径  --><javaModelGeneratortargetPackage="com.hyx.springboot03.model"targetProject="src/main/java"><!-- 是否允许子包,即targetPackage.schemaName.tableName --><propertyname="enableSubPackages"value="false"/><!-- 是否对model添加构造函数 --><propertyname="constructorBased"value="true"/><!-- 是否针对string类型的字段在set的时候进行trim调用 --><propertyname="trimStrings"value="false"/><!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 --><propertyname="immutable"value="false"/></javaModelGenerator><!-- 02 指定sql映射文件生成的位置 --><sqlMapGeneratortargetPackage="com.hyx.springboot03.mapper"targetProject="src/main/resources"><!-- 是否允许子包,即targetPackage.schemaName.tableName --><propertyname="enableSubPackages"value="false"/></sqlMapGenerator><!-- 03 生成XxxMapper接口 --><!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --><!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --><!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --><javaClientGeneratortargetPackage="com.hyx.springboot03.mapper"targetProject="src/main/java"type="XMLMAPPER"><!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --><propertyname="enableSubPackages"value="false"/></javaClientGenerator><!-- 配置表信息 --><!-- schema即为数据库名 --><!-- tableName为对应的数据库表 --><!-- domainObjectName是要生成的实体类 --><!-- enable*ByExample是否生成 example类 --><!--<table schema="" tableName="t_book" domainObjectName="Book"--><!--enableCountByExample="false" enableDeleteByExample="false"--><!--enableSelectByExample="false" enableUpdateByExample="false">--><!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;--><!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;--><!--&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;--><!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;--><!--</table>--><tableschema=""tableName="customer"domainObjectName="Customer"enableCountByExample="false"enableDeleteByExample="false"enableSelectByExample="false"enableUpdateByExample="false"></table></context></generatorConfiguration>

image-20230809213624464

1.3在pom中添加插件

<plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.2</version><dependencies><!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency></dependencies><configuration><overwrite>true</overwrite></configuration></plugin>

1.4测试

image-20230809200750255

image-20230809201234798

1.5.新建一个controller包,添加JdbcController

packagecom.hyx.springboot03.controller;importcom.hyx.springboot03.mapper.CustomerMapper;importcom.hyx.springboot03.model.Customer;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.*;@RestController@RequestMapping("/jdbc")publicclassJdbcController{@AutowiredpublicCustomerMapper customerMapper;@GetMapping("/get")publicCustomerlist(Integer cid){return customerMapper.selectByPrimaryKey(cid);}@DeleteMapping("/delete")publicintdelete(Integer cid){return customerMapper.deleteByPrimaryKey(cid);}@PostMapping("/add")publicintadd(Customer customer){return customerMapper.insertSelective(customer);}}

问题解决Could not autowire. No beans of ‘customerMapper‘ type found.

image-20230809201637152

还要修改启动类,在启动类上加上@mapperScan(“com.hyx.springboot03.mapper”)

image-20230809214641760

不然启动就会出现以下问题

Field customerMapper in com.hyx.springboot03.controller.JdbcController required a bean of type 'com.hyx.springboot03.mapper.CustomerMapper' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.hyx.springboot03.mapper.CustomerMapper' in your configuration.

image-20230809215249247

好,当我们修改完成后

1.6启动项目

发送请求,成功返回数据

image-20230809214438272

image-20230809220726068

2.整合MybatisPlus

2.1添加依赖

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency>

application.yml

server:port:8082spring:application:name: springboot03
  datasource:driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8password:123456username: root
logging:level:com.hyx.springboot03: debug
mybatis-plus:mapper-locations: classpath:mappers/**/*.xmltype-aliases-package: com.hyx.springboot03.model

2.2添加MyBatis配置类

packagecom.hyx.springboot03.mp;importcom.baomidou.mybatisplus.annotation.DbType;importcom.baomidou.mybatisplus.annotation.IdType;importcom.baomidou.mybatisplus.core.exceptions.MybatisPlusException;importcom.baomidou.mybatisplus.core.toolkit.StringPool;importcom.baomidou.mybatisplus.core.toolkit.StringUtils;importcom.baomidou.mybatisplus.generator.AutoGenerator;importcom.baomidou.mybatisplus.generator.InjectionConfig;importcom.baomidou.mybatisplus.generator.config.*;importcom.baomidou.mybatisplus.generator.config.po.TableInfo;importcom.baomidou.mybatisplus.generator.config.rules.NamingStrategy;importcom.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;importjava.util.ArrayList;importjava.util.List;importjava.util.Scanner;/**
 * mybatis-plus代码生成
 */publicclassMPGenerator{/**
     * <p>
     * 读取控制台内容
     * </p>
     */publicstaticStringscanner(String tip){Scanner scanner =newScanner(System.in);StringBuilder help =newStringBuilder();
        help.append("请输入"+ tip);System.out.println(help.toString());if(scanner.hasNext()){String ipt = scanner.next();if(StringUtils.isNotBlank(ipt)){if("quit".equals(ipt))return"";return ipt;}}thrownewMybatisPlusException("请输入正确的"+ tip +"!");}publicstaticvoidmain(String[] args){// 代码生成器AutoGenerator mpg =newAutoGenerator();// 1.全局配置GlobalConfig gc =newGlobalConfig();String projectPath =System.getProperty("user.dir")+"/SpringBoot03";System.out.println(projectPath);

        gc.setOutputDir(projectPath +"/src/main/java");
        gc.setOpen(false);
        gc.setBaseResultMap(true);//生成BaseResultMap
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList//gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setAuthor("lky");// 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");

        gc.setIdType(IdType.AUTO);
        mpg.setGlobalConfig(gc);// 2.数据源配置DataSourceConfig dsc =newDataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setUrl("jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);// 3.包配置PackageConfig pc =newPackageConfig();String moduleName =scanner("模块名(quit退出,表示没有模块名)");if(StringUtils.isNotBlank(moduleName)){
            pc.setModuleName(moduleName);}
        pc.setParent("com.hyx.springboot03").setMapper("mapper").setService("service").setController("controller").setEntity("model");
        mpg.setPackageInfo(pc);// 4.自定义配置InjectionConfig cfg =newInjectionConfig(){@OverridepublicvoidinitMap(){// to do nothing}};// 如果模板引擎是 freemarkerString templatePath ="/templates/mapper.xml.ftl";// 自定义输出配置List<FileOutConfig> focList =newArrayList<>();// 自定义配置会被优先输出
        focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfo tableInfo){// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!if(StringUtils.isNotBlank(pc.getModuleName())){return projectPath +"/src/main/resources/mapper/"+ pc.getModuleName()+"/"+ tableInfo.getEntityName()+"Mapper"+StringPool.DOT_XML;}else{return projectPath +"/src/main/resources/mapper/"+ tableInfo.getEntityName()+"Mapper"+StringPool.DOT_XML;}}});
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig =newTemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);// 5.策略配置StrategyConfig strategy =newStrategyConfig();// 表名生成策略(下划线转驼峰命名)
        strategy.setNaming(NamingStrategy.underline_to_camel);// 列名生成策略(下划线转驼峰命名)
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);// 是否启动Lombok配置
        strategy.setEntityLombokModel(true);// 是否启动REST风格配置
        strategy.setRestControllerStyle(true);// 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");// 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");// 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");// 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
        strategy.setSuperEntityColumns("id");// 写于父类中的公共字段plus
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);//表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
        strategy.setTablePrefix("t_","t_sys_");//strategy.setTablePrefix(scanner("请输入表前缀"));
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(newFreemarkerTemplateEngine());// 执行
        mpg.execute();}}

2.3启动配置类

image-20230809222717806

image-20230809223437643

2.4发现一个问题,MyBatisPlus自动生成的实体类没有主键,已手动添加

image-20230809225440919

2.5然后测试一下查询接口,成功

image-20230809225319228

2.6MyBatisPlus使用多表联查

2.6.1在UserService中添加
List<Map>queryUserRole(Map map);
2.6.2在UserServiceImpl中添加
@AutowiredprivateUserMapper userMapper;@OverridepublicList<Map>queryUserRole(Map map){return userMapper.queryUserRole(map);}
2.6.3在UserMapper接口上添加
@Select("SELECT u.id,u.user_name,u.true_name,r.role_name FROM t_user u,t_role r WHERE u.roleId=r.id AND u.roleId='17'")List<Map>queryUserRole(Map map);
2.6.5在UserController中添加
// 连表查询@GetMapping("/userRole")publicList<Map>userRole(String userName){Map map =newHashMap();
        map.put("user_name",userName);List<Map> maps = userService.queryUserRole(map);return maps;}
2.6.6两表联查成功

image-20230809231237188

标签: spring boot mybatis

本文转载自: https://blog.csdn.net/qq_52642109/article/details/132199835
版权归原作者 渡边彻彻泽一 所有, 如有侵权,请联系我们删除。

“SpringBoot(3)整合MyBatis 和MybatisPlus”的评论:

还没有评论