1.MyBatis Generator简介

MyBatis Generator是Mybatis的代码生成器,可以根据数据库表单逆向生成对应的PoJoMapper类以及Mapper.xml文件。使用Generator生成器在一定程度上可以减轻我们的工作量,避免重复劳动。

MyBatis Generator官网:http://mybatis.org/generator/index.html

 

1.1.SpringBoot基于IDEA项目整合MyBatis Generator

博文链接:【java框架】SpringBoot(7) -- SpringBoot整合MyBatis

本博客基于上一篇博文工程来进行整合测试,下面给出主要代码,完整代码不再罗列,具体看链接就可以了。

①首先在IDEA中需要安装idea-mybatis-generator插件:

 

 ②Maven管理工具中引入mybatis-generator,需要在pom.xml中加入plugin配置:

 <!--引入mybatis逆向工程插件-->
 <plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.5</version>
     <configuration>                 
            <configurationFile>${basedir}/src/main/resources/mybatis-generator/generatorConfig.xml
            </configurationFile>
            <overwrite>true</overwrite>
            <verbose>true</verbose>
     </configuration>
 </plugin>

这样在IDEA Maven工具栏中就有了mybatis-generator编译插件:

 

1.2.数据库建表及配置xml文件

①创建测试表单sql语句:

这边利用这张数据库表单来生成测试逆向工程

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;


DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `productName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品名称',
  `dir_id` bigint(11) NULL DEFAULT NULL COMMENT '商品分类编号',
  `salePrice` double(10, 2) NULL DEFAULT NULL COMMENT '零售价',
  `supplier` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '供应商',
  `brand` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '品牌',
  `cutoff` double(2, 2) NULL DEFAULT NULL COMMENT '折扣比例',
  `costPrice` double(10, 2) NULL DEFAULT NULL COMMENT '进价',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 33 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `product` VALUES (1, '罗技M90', 3, 90.00, '罗技', '罗技', 0.50, 35.00);
INSERT INTO `product` VALUES (2, '罗技M100', 3, 49.00, '罗技', '罗技', 0.90, 33.00);
INSERT INTO `product` VALUES (3, '罗技M115', 3, 99.00, '罗技', '罗技', 0.60, 38.00);
INSERT INTO `product` VALUES (4, '罗技M125', 3, 80.00, '罗技', '罗技', 0.90, 39.00);
INSERT INTO `product` VALUES (5, '罗技木星轨迹球', 3, 182.00, '罗技', '罗技', 0.80, 80.00);
INSERT INTO `product` VALUES (6, '罗技火星轨迹球', 3, 349.00, '罗技', '罗技', 0.87, 290.00);
INSERT INTO `product` VALUES (7, '罗技G9X', 3, 680.00, '罗技', '罗技', 0.70, 470.00);
INSERT INTO `product` VALUES (8, '罗技M215', 2, 89.00, '罗技', '罗技', 0.79, 30.00);
INSERT INTO `product` VALUES (9, '罗技M305', 2, 119.00, '罗技', '罗技', 0.82, 48.00);
INSERT INTO `product` VALUES (10, '罗技M310', 2, 135.00, '罗技', '罗技', 0.92, 69.80);
INSERT INTO `product` VALUES (11, '罗技M505', 2, 148.00, '罗技', '罗技', 0.92, 72.00);
INSERT INTO `product` VALUES (12, '罗技M555', 2, 275.00, '罗技', '罗技', 0.88, 140.00);
INSERT INTO `product` VALUES (13, '罗技M905', 2, 458.00, '罗技', '罗技', 0.88, 270.00);
INSERT INTO `product` VALUES (14, '罗技MX1100', 2, 550.00, '罗技', '罗技', 0.76, 300.00);
INSERT INTO `product` VALUES (15, '罗技M950', 2, 678.00, '罗技', '罗技', 0.78, 320.00);
INSERT INTO `product` VALUES (16, '罗技MX Air', 2, 1299.00, '罗技', '罗技', 0.72, 400.00);
INSERT INTO `product` VALUES (17, '罗技G1', 4, 155.00, '罗技', '罗技', 0.80, 49.00);
INSERT INTO `product` VALUES (18, '罗技G3', 4, 229.00, '罗技', '罗技', 0.77, 96.00);
INSERT INTO `product` VALUES (19, '罗技G500', 4, 399.00, '罗技', '罗技', 0.88, 130.00);
INSERT INTO `product` VALUES (20, '罗技G700', 4, 699.00, '罗技', '罗技', 0.79, 278.00);
INSERT INTO `product` VALUES (21, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (22, '测试产品114', 4, 520.10, '甲骨文114', 'TestBrand114', 0.45, 237.10);
INSERT INTO `product` VALUES (23, '测试产品114', 4, 520.10, '甲骨文114', 'TestBrand114', 0.45, 237.10);
INSERT INTO `product` VALUES (25, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (26, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (27, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (28, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (29, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (30, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (31, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);
INSERT INTO `product` VALUES (32, '测试产品112', 4, 520.00, '甲骨文', 'TestBrand', 0.85, 237.50);

SET FOREIGN_KEY_CHECKS = 1;
View Code

②项目中添加MyBatis Generator逆向工程需要的配置文件,需要在resources目录下创建mybatis-generator文件,用于存放:

具体项目示意图如下:

generator.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username=root
password=admin

generatorConfig.xml

主要修改点已标黄

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--需要单独引入generator.properties数据源格式配置文件-->
    <properties resource="mybatis-generator/generator.properties"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接参数 -->
        <jdbcConnection
                driverClass="${driverClassName}"
                connectionURL="${url}"
                userId="${username}"
                password="${password}">
        </jdbcConnection>
        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 实体类的包名和存放路径 -->
        <javaModelGenerator targetPackage="com.fengye.springboot_mybatis.entity" targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <!--<property name="constructorBased" value="true"/>-->
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变。即生成的Model对象不会有 setter方法,只有构造方法 -->
            <!--<property name="immutable" value="false"/>-->
        </javaModelGenerator>

        <!-- 生成映射文件*maper.xml的位置-->
        <sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成mapper接口文件位置 -->
        <javaClientGenerator type ="XMLMAPPER" targetPackage="com.fengye.springboot_mybatis.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- tableName:数据库中的表名或视图名;domainObjectName:生成的实体类的类名-->
        <table tableName="product" domainObjectName="Product"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        <!--区分大小写,与数据库保持一致-->
        <!--<property name= "useActualColumnNames" value= "true"/>-->
        </table>
    </context>
</generatorConfiguration>

 

1.3.执行插件测试验证

在项目Maven工具栏中执行引入的mybatis-generator生成器进行自动构建生成:

 

运行构建成功之后,可以看到对应数据库表product的domain、mapper、mapper.xml文件已经生成了!

 

1.4.问题小插曲

实际在执行mybatis-generator:generate进行自动构建时可能会由于找不到mysql驱动jar包而Build Failed异常:

[ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project springboot_mybatis: Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate failed: Exception getting JDBC Driver: com.mysql.cj.jdbc.Driver -> [Help 1]

需要在pom.xml中添加驱动包构建版本配置,即指定一下编译构建需要的mysql驱动版本,因为我项目中用到的是mysql8的版本,驱动不是jdbc:

pom.xml增加如下配置:

 <!--引入mybatis逆向工程插件-->
 <plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.5</version>
     <configuration>
         <configurationFile>${basedir}/src/main/resources/mybatis-generator/generatorConfig.xml
         </configurationFile>
         <overwrite>true</overwrite>
         <verbose>true</verbose>
     </configuration>
     <!--此处必须添加mysql驱动包-->
     <dependencies>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <scope>runtime</scope>
             <version>8.0.23</version>
         </dependency>
     </dependencies>
 </plugin>

1.5.使用Java代码方式生成Mapper

 除了使用maven插件的方式,Mybatis Gennerator还提供了使用Java测试类方式生成对应的JavaBean、Mapper、以及PojoExample查询类:

@SpringBootTest
class SpringbootMybatisApplicationTests {
    @Test
    public void testMybatisGenerator() throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
     // 这里需要使用绝对路径进行生成 File configFile
= new File("E:\\Workspaces\\SpringBoot_Study\\springboot_mybatis\\src\\main\\resources\\mybatis-generator\\generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }

如果需要生成对应的Example查询器,需要在generatorConfig.xml中做如下配置,主要将标黄的地方修改为true:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--需要单独引入generator.properties数据源格式配置文件-->
    <properties resource="mybatis-generator/generator.properties"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制
             是否强制转换数据库类型BigDecimal-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- javaModelGenerator:指定javaBean的生成策略
             targetPackage:目标类包名
             targetProject:目标工程目录
             配置指定实体类的包名和存放路径 -->
        <javaModelGenerator targetPackage="com.fengye.springboot_mybatis.entity" targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <!--<property name="constructorBased" value="true"/>-->
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变。即生成的Model对象不会有 setter方法,只有构造方法 -->
            <!--<property name="immutable" value="false"/>-->
        </javaModelGenerator>

        <!-- sqlMapGenerator:sql映射生成的策略
             配置指定生成映射文件*maper.xml的位置-->
        <sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- table配置指定要逆向分析生成哪些表,根据表创建javaBean对象,可以配置多个
             tableName:数据库中的表名或视图名;domainObjectName:生成的实体类的类名-->
        <table tableName="product" domainObjectName="Product"
               enableCountByExample="true" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="true"
               selectByExampleQueryId="false">
        <!--区分大小写,与数据库保持一致-->
        <!--<property name= "useActualColumnNames" value= "true"/>-->
        </table>
    </context>
</generatorConfiguration>

1.6.使用XxxExample

使用MyBatis Generator生成器利用1.5中的配置可以生成selectByExample和ProductExample,及查询条件封装器,可以不用写sqlMapper语句,直接进行一些查询条件的封装进行查询数据返回。具体使用如下:

@RestController
public class ProController {
    @Autowired
    private ProductMapper productMapper;

    @RequestMapping("/getExample")
    public List<Product> getProductFromExample() {
        // xxxByExample可以封装内部的查询条件
        // 1.查询所有
        List<Product> productList = productMapper.selectByExample(null);
        // 2.查询产品名称包含"M2"的,并且价格在50-100之间的产品
        ProductExample example = new ProductExample();
        // criteria可以拼装查询条件
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andProductnameLike("%M2%").andSalepriceBetween(50.00, 100.00);

        //3.查询产品名称包含"G1"的,需要两个criteria拼接or的关系
        ProductExample.Criteria criteria2 = example.createCriteria();
        String[] bands = {"罗技", "TestBrand"};
        criteria.andBrandIn(Arrays.asList(bands));
        //使用example.or来拼接另一个criteria
        example.or(criteria2);

        List<Product> selectProducts = productMapper.selectByExample(example);
        return selectProducts;
    }
}

 

博客写作参考博文:

MyBatis Generator官网

MyBatis Generator使用方法

 

博客涉及代码示例均已上传至Github专区:

SpringBootStudy

 

posted on 2021-05-12 13:23  人无名,则可专心练剑  阅读(419)  评论(0编辑  收藏  举报