使用mybatis-generator的一些总结

        MyBatis-Generator是MyBatis的代码生成器,它为所有版本的MyBatis生成代码。会内省数据库表(或许多表)。内省数据库表(或许多表),并生成可用于访问这些表的工件,这极大地减少了设置对象和配置文件以与数据库表交互的初始麻烦。

在学习使用的过程中,发现有两种使用方式,一种是插件形式(操作简单,使用方便),还有一种类似的,添加一些自定义配置(更为灵活);

1、使用环境

mysql8.0,mybatis-plus3.1.2,mybatis-generator-core1.3.5

2、使用方式

1、引用依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.14</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

除了依赖,还要在pom文件配置插件(插件方式,需要配置;自定义方式,可以忽略)

注意:

a、需要注意依赖和插件中配置的版本一致

b、配置文件名称与下一步要配置的文件名称一致

             <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.14</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <!--允许移动生成的文件-->
                    <verbose>true</verbose>
                    <!--允许自动覆盖文件,第一次可覆盖,以后都不可覆盖-->
                    <overwrite>true</overwrite>
                    <!-- 自定义配置文件的名称  默认是generatorConfig.xml -->
                    <configurationFile>
                        src/main/resources/mybatis-generator.xml
                    </configurationFile>
                </configuration>
            </plugin>

2、配置文件

2.1、在src/main/resources下创建文件mybatis-generator.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>
    <context id="mysqlGenerator" targetRuntime="MyBatis3">
<!--        (自定义方式,需要配置;插件方式,需要忽略)-->
<!--        <plugin type="com.config.MyBatisPlugin" >-->
<!--            <property name="hasLombok" value="true"/>-->
<!--        </plugin>-->
        <!--关闭注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.0.108/test?useSSL=false"
                        userId="root"
                        password="123456">
            <!--MySQL 8.x 需要指定服务器的时区-->
            <property name="serverTimezone" value="UTC"/>
            <!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
            <!--参考 : http://www.mybatis.org/generator/usage/mysql.html-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>
        <javaModelGenerator targetPackage="com.situation.entity" targetProject="src/main/java" />
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources" />
        <javaClientGenerator targetPackage="com.situation.mapper" targetProject="src/main/java" type="XMLMAPPER" />
        <table tableName="t_report_info"
               domainObjectName="ReportInfo"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableDeleteByPrimaryKey="false"
               enableSelectByPrimaryKey="false"
               enableUpdateByPrimaryKey="true">

            <!--驼峰-->
            <property name="useActualColumnNames" value="true" />
            <columnOverride column="mainBody" jdbcType="VARCHAR"/> <!--解决长文本生成带WithBLOBs问题-->
            <!--忽略生成的字段 (此操作会导致生成的mapper文件,无法生成update,delete等方法)-->
<!--            <ignoreColumn column="creatorId"/>-->
        </table>

    </context>
</generatorConfiguration>

2.2、自定义配置(自定义方式可以选择使用,插件方式不需要)

public class MyBatisPlugin extends PluginAdapter {

    @Override
    public boolean validate(List<String> list) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        //添加domain的import
        topLevelClass.addImportedType("lombok.Data");

        //添加domain的注解
        topLevelClass.addAnnotation("@Data");

        topLevelClass.addJavaDocLine("/**");

        String remarks = introspectedTable.getRemarks();
        if (StringUtility.stringHasValue(remarks)) {
            String[] remarkLines = remarks.split(System.getProperty("line.separator"));
            for (String remarkLine : remarkLines) {
                topLevelClass.addJavaDocLine(" * " + remarkLine);
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(" * ").append(introspectedTable.getFullyQualifiedTable());
        topLevelClass.addJavaDocLine(sb.toString());
        sb.setLength(0);
        sb.append(" * @author ").append(System.getProperties().getProperty("user.name"));
        topLevelClass.addJavaDocLine(sb.toString());
        sb.setLength(0);
        sb.append(" * @date ");
        sb.append(getDateString());
        topLevelClass.addJavaDocLine(sb.toString());
        topLevelClass.addJavaDocLine(" */");
        return true;
    }

    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
                                       IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        field.addJavaDocLine("/**");
        String remarks = introspectedColumn.getRemarks();
        if (StringUtility.stringHasValue(remarks)) {
            String[] remarkLines = remarks.split(System.getProperty("line.separator"));
            for (String remarkLine : remarkLines) {
                field.addJavaDocLine(" * " + remarkLine);
            }
        }
        field.addJavaDocLine(" */");
        return true;
    }

    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        //添加Mapper的import
        interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper"));
        //添加Mapper的注解
        interfaze.addAnnotation("@Mapper");
        return true;
    }

    @Override
    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        //不生成getter
        return false;
    }

    @Override
    public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        //不生成setter
        return false;
    }

    protected String getDateString() {
//        return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        return null;
    }
}

2.3、添加启动类(自定义方式可以选择使用,插件方式不需要)

public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(MyBatisGen.class.getClassLoader().getResourceAsStream("generatorConfig.xml"));
        // 解决IDEA下运行,多个模块路径冲突问题,不然找不到
        String cpath = MyBatisGen.class.getClassLoader().getResource("generatorConfig.xml").toString();
        cpath = cpath.substring(0, cpath.indexOf("target")).replace("file:/", "");
        Context context = config.getContexts().get(0);
        context.getJavaModelGeneratorConfiguration().setTargetProject(cpath+context.getJavaModelGeneratorConfiguration().getTargetProject());
        context.getSqlMapGeneratorConfiguration().setTargetProject(cpath+context.getSqlMapGeneratorConfiguration().getTargetProject());
        context.getJavaClientGeneratorConfiguration().setTargetProject(cpath+context.getJavaClientGeneratorConfiguration().getTargetProject());
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }

3、操作使用

3.1、插件方式使用

在idea中找到并双击启动

3.2、自定义方式使用

点击启动上面配置的main方法即可

3.3、执行成功

这样就可以成功使用了。

如果有什么使用疑问,请在评论区留言交流

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值