MyBatis Generator:使用中的问题和解决办法

1.声明

当前内容主要为使用和测试MyBatis Generator,实现对MyBatis代码的生成,以及解决其中的问题

当前版本:

  1. MyBatis 3.2.2
  2. mybatis-generator-core 1.3.6

2.当前生成器的demo

当前的

<?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>
	<properties resource="db.properties"/>
  	<context id="MySql" targetRuntime="MyBatis3">
  		
          <!-- 生成的 Java 文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化 Java 代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化 XML 代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useSSL=false"
                        userId="root"
                        password="root">
        </jdbcConnection> -->
        <jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
        </jdbcConnection>
        <!--生成entity类存放位置-->
        <javaModelGenerator targetPackage="com.app.entity" targetProject="MGTestProject/src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.app.mapper" targetProject="MGTestProject/src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.app.dao" targetProject="MGTestProject/src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 下面就是导出的表 -->
        <!-- 其中的tableName="%"表示的就是生成当前数据库中的所有表 -->
        <table tableName="user" domainObjectName="User" enableSelectByExample="false" enableDeleteByExample="false"
				enableCountByExample="false" enableUpdateByExample="false">
	      <property name="useActualColumnNames" value="true"/>
	    
	      <generatedKey column="id" sqlStatement="Mysql" identity="true"  />
	      <!-- <columnOverride column="DATE_FIELD" property="startDate" />
	      <ignoreColumn column="FRED" />
	      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
	    </table>
    </context>
</generatorConfiguration>

生成器.java

public class MyBatisCodeGenerator {
    
    

    public static void main(String[] args) throws Exception{
    
    
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        URL resource = MyBatisGenerator.class.getClassLoader().getResource("");
        String generatorFile = resource.getPath()+"/generator/generatorConfig.xml";
        File configFile = new File(generatorFile);
        if(!configFile.exists()) {
    
    
        	System.out.println("当前生产器的配置文件不存在!:"+generatorFile);
        	return;
        }
        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);
        // 无法获取当前的警告消息,一般未出现任何代码或者生成文件那么一般就表示当前的生成的路径不正确
        if(warnings.isEmpty()) {
    
    
        	
        }else {
    
    
        	for (String warning : warnings) {
    
    
				System.out.println(warning);
			}
        }
        System.out.println("生成代码成功.........");
    }
}

当前项目结构:
在这里插入图片描述

2.问题1:不生成代码问题

通过debug发现当前的MyBatis生成器并不会报错,只会生成警告!原因在代码部分:

 private void writeGeneratedXmlFile(GeneratedXmlFile gxf, ProgressCallback callback)
            throws InterruptedException, IOException {
    
    
        File targetFile;
        String source;
        try {
    
    
            File directory = shellCallback.getDirectory(gxf
                    .getTargetProject(), gxf.getTargetPackage());
            targetFile = new File(directory, gxf.getFileName());
            if (targetFile.exists()) {
    
    
                if (gxf.isMergeable()) {
    
    
                    source = XmlFileMergerJaxp.getMergedSource(gxf,
                            targetFile);
                } else if (shellCallback.isOverwriteEnabled()) {
    
    
                    source = gxf.getFormattedContent();
                    warnings.add(getString("Warning.11", //$NON-NLS-1$
                            targetFile.getAbsolutePath()));
                } else {
    
    
                    source = gxf.getFormattedContent();
                    targetFile = getUniqueFileName(directory, gxf
                            .getFileName());
                    warnings.add(getString(
                            "Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$
                }
            } else {
    
    
                source = gxf.getFormattedContent();
            }

            callback.checkCancel();
            callback.startTask(getString(
                    "Progress.15", targetFile.getName())); //$NON-NLS-1$
            writeFile(targetFile, source, "UTF-8"); //$NON-NLS-1$
        } catch (ShellException e) {
    
    
            warnings.add(e.getMessage());
        }
    }

其他的生成文件和这个一样,其中的错误都被捕获了,只是作为警告显示出来,所以前台可以打印警告!

出现该问题的实际原因:无法获取当前的输出文件夹:targetProject="MGTestProject/src",所以需要修改为相对路径targetProject="./src",改变路径即可,最后生成成功!

3.问题2:生成其他数据库的表?

本人明确指定了当前的连接字符串并带有数据库结果:还是生成其他库的相同表对应的文件!(递归查找了所有符合tableName的表)

db.properties的内容

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

其中生成的结果:

扫描二维码关注公众号,回复: 12724426 查看本文章
2021-02-17 09:22:05 Logging initialized using 'org.mybatis.generator.logging.log4j.Log4jLoggingLogFactory@4c70fda8' adapter.
2021-02-17 09:22:05 Retrieving column information for table "user"
2021-02-17 09:22:05 Found column "id", data type 4, in table "c_project_test..user"
2021-02-17 09:22:05 Found column "name", data type 1, in table "c_project_test..user"
2021-02-17 09:22:05 Found column "age", data type 4, in table "c_project_test..user"
2021-02-17 09:22:05 Found column "sex", data type 1, in table "c_project_test..user"
2021-02-17 09:22:05 Found column "email", data type 1, in table "c_project_test..user"
2021-02-17 09:22:05 Found column "Host", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "User", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Select_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Insert_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Update_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Delete_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Drop_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Reload_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Shutdown_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Process_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "File_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Grant_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "References_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Index_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Alter_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Show_db_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Super_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_tmp_table_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Lock_tables_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Execute_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Repl_slave_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Repl_client_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_view_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Show_view_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_routine_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Alter_routine_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_user_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Event_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Trigger_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "Create_tablespace_priv", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "ssl_type", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "ssl_cipher", data type -4, in table "mysql..user"
2021-02-17 09:22:05 Found column "x509_issuer", data type -4, in table "mysql..user"
2021-02-17 09:22:05 Found column "x509_subject", data type -4, in table "mysql..user"
2021-02-17 09:22:05 Found column "max_questions", data type 4, in table "mysql..user"
2021-02-17 09:22:05 Found column "max_updates", data type 4, in table "mysql..user"
2021-02-17 09:22:05 Found column "max_connections", data type 4, in table "mysql..user"
2021-02-17 09:22:05 Found column "max_user_connections", data type 4, in table "mysql..user"
2021-02-17 09:22:05 Found column "plugin", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "authentication_string", data type -1, in table "mysql..user"
2021-02-17 09:22:05 Found column "password_expired", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "password_last_changed", data type 93, in table "mysql..user"
2021-02-17 09:22:05 Found column "password_lifetime", data type 5, in table "mysql..user"
2021-02-17 09:22:05 Found column "account_locked", data type 1, in table "mysql..user"
2021-02-17 09:22:05 Found column "id", data type 4, in table "test..user"
2021-02-17 09:22:05 Found column "name", data type 12, in table "test..user"
2021-02-17 09:22:05 Found column "pwd", data type 12, in table "test..user"
2021-02-17 09:22:05 Found column "age", data type 4, in table "test..user"
2021-02-17 09:22:05 Found column "adress", data type 12, in table "test..user"
2021-02-17 09:22:05 Found column "createTime", data type 93, in table "test..user"
Table Configuration user matched more than one table (test..user,mysql..user,c_project_test..user)
Cannot obtain primary key information from the database, generated objects may be incomplete
Cannot obtain primary key information from the database, generated objects may be incomplete
Cannot obtain primary key information from the database, generated objects may be incomplete
Column id, specified as an identity column in table user, does not exist in the table.
Existing file D:\eclipse-workspace\MGTestProject\.\src\com\app\entity\User.java was overwritten
Existing file D:\eclipse-workspace\MGTestProject\.\src\com\app\dao\UserMapper.java was overwritten
Existing file D:\eclipse-workspace\MGTestProject\.\src\com\app\entity\User.java was overwritten
Existing file D:\eclipse-workspace\MGTestProject\.\src\com\app\dao\UserMapper.java was overwritten

当前出现这种结果的的问题原因(竟然连mysql.user也获取到生成了...无语):

  1. 使用了当前的mysql数据库驱动版本为6.0.6
  2. 使用驱动为:com.mysql.cj.jdbc.Driver
    说起来就是当前的mysql的版本太高导致的:解决办法(修改当前的数据库版本为5.XX的)

解决后:

1.mysql-connector-java:5.1.12版本
2.db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false
jdbc.username=root
jdbc.password=root

再次测试的结果:

2021-02-17 09:26:49 Logging initialized using 'org.mybatis.generator.logging.log4j.Log4jLoggingLogFactory@3a4afd8d' adapter.
2021-02-17 09:26:49 Retrieving column information for table "user"
2021-02-17 09:26:49 Found column "id", data type 4, in table "test..user"
2021-02-17 09:26:49 Found column "name", data type 12, in table "test..user"
2021-02-17 09:26:49 Found column "pwd", data type 12, in table "test..user"
2021-02-17 09:26:49 Found column "age", data type 4, in table "test..user"
2021-02-17 09:26:49 Found column "adress", data type 12, in table "test..user"
2021-02-17 09:26:49 Found column "createTime", data type 93, in table "test..user"

只生成当前数据库中的指定user表了

4.总结

  1. 使用代码生成器生成后很方便,但是也存在各种问题,小心路径输出地址
  2. 小心当前的数据库驱动版本,否则会生成其他数据库的表

猜你喜欢

转载自blog.csdn.net/weixin_45492007/article/details/113831084