Search in sources :

Example 11 with InvalidConfigurationException

use of org.mybatis.generator.exception.InvalidConfigurationException in project generator by mybatis.

the class MyBatisGeneratorMojo method execute.

@Override
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("MyBatis generator is skipped.");
        return;
    }
    saveClassLoader();
    LogFactory.setLogFactory(new MavenLogFactory(this));
    calculateClassPath();
    // add resource directories to the classpath.  This is required to support
    // use of a properties file in the build.  Typically, the properties file
    // is in the project's source tree, but the plugin classpath does not
    // include the project classpath.
    List<Resource> resources = project.getResources();
    List<String> resourceDirectories = new ArrayList<>();
    for (Resource resource : resources) {
        resourceDirectories.add(resource.getDirectory());
    }
    ClassLoader cl = ClassloaderUtility.getCustomClassloader(resourceDirectories);
    ObjectFactory.addExternalClassLoader(cl);
    if (configurationFile == null) {
        throw new MojoExecutionException(// $NON-NLS-1$
        Messages.getString("RuntimeError.0"));
    }
    List<String> warnings = new ArrayList<>();
    if (!configurationFile.exists()) {
        throw new MojoExecutionException(Messages.getString("RuntimeError.1", // $NON-NLS-1$
        configurationFile.toString()));
    }
    runScriptIfNecessary();
    Set<String> fullyqualifiedTables = new HashSet<>();
    if (StringUtility.stringHasValue(tableNames)) {
        // $NON-NLS-1$
        StringTokenizer st = new StringTokenizer(tableNames, ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                fullyqualifiedTables.add(s);
            }
        }
    }
    Set<String> contextsToRun = new HashSet<>();
    if (StringUtility.stringHasValue(contexts)) {
        // $NON-NLS-1$
        StringTokenizer st = new StringTokenizer(contexts, ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                contextsToRun.add(s);
            }
        }
    }
    try {
        ConfigurationParser cp = new ConfigurationParser(project.getProperties(), warnings);
        Configuration config = cp.parseConfiguration(configurationFile);
        ShellCallback callback = new MavenShellCallback(this, overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(new MavenProgressCallback(getLog(), verbose), contextsToRun, fullyqualifiedTables);
    } catch (XMLParserException e) {
        for (String error : e.getErrors()) {
            getLog().error(error);
        }
        throw new MojoExecutionException(e.getMessage());
    } catch (SQLException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (InvalidConfigurationException e) {
        for (String error : e.getErrors()) {
            getLog().error(error);
        }
        throw new MojoExecutionException(e.getMessage());
    } catch (InterruptedException e) {
    // ignore (will never happen with the DefaultShellCallback)
    }
    for (String error : warnings) {
        getLog().warn(error);
    }
    if (project != null && outputDirectory != null && outputDirectory.exists()) {
        project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
        Resource resource = new Resource();
        resource.setDirectory(outputDirectory.getAbsolutePath());
        resource.addInclude("**/*.xml");
        project.addResource(resource);
    }
    restoreClassLoader();
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Configuration(org.mybatis.generator.config.Configuration) ShellCallback(org.mybatis.generator.api.ShellCallback) XMLParserException(org.mybatis.generator.exception.XMLParserException) SQLException(java.sql.SQLException) Resource(org.apache.maven.model.Resource) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) StringTokenizer(java.util.StringTokenizer) ConfigurationParser(org.mybatis.generator.config.xml.ConfigurationParser) HashSet(java.util.HashSet) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 12 with InvalidConfigurationException

use of org.mybatis.generator.exception.InvalidConfigurationException in project mybatis-generator-gui-extension by spawpaw.

the class MBGRunner method generate.

public String generate() throws SQLException {
    config = new Configuration();
    // default model type
    if (projectConfig.defaultModelType.getValue().equalsIgnoreCase("CONDITIONAL"))
        context = new Context(ModelType.CONDITIONAL);
    else if (projectConfig.defaultModelType.getValue().equalsIgnoreCase("FLAT"))
        context = new Context(ModelType.FLAT);
    else
        context = new Context(ModelType.HIERARCHICAL);
    // id
    context.setId("mybatis generator gui extension");
    // targetRuntime
    context.setTargetRuntime("MyBatis3");
    context.addProperty("javaFileEncoding", projectConfig.javaFileEncoding.getValue());
    for (Map.Entry<String, String> tableDDL : databaseConfig.tableDDLs.entrySet()) {
        context.addProperty("ddls." + tableDDL.getKey(), tableDDL.getValue());
        log.info("add config [{}:{}] to context", "ddls." + tableDDL.getKey(), tableDDL.getValue());
    }
    // =====================================================================================================加载插件
    // initialize plugin data
    initPluginConfigs();
    addPlugins();
    // ====================================================================================================注释生成器
    if (projectConfig.enableComment.getValue()) {
        CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
        commentGeneratorConfiguration.setConfigurationType(DeclaredPlugins.CommentPlugin);
        if (pluginConfigs.containsKey(DeclaredPlugins.CommentPlugin)) {
            HashMap<String, String> pluginProperties = pluginConfigs.get(DeclaredPlugins.CommentPlugin);
            for (String key : pluginProperties.keySet()) commentGeneratorConfiguration.addProperty(key, pluginProperties.get(key));
        }
        context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);
    } else {
        CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
        commentGeneratorConfiguration.addProperty("suppressDate", "true");
        commentGeneratorConfiguration.addProperty("suppressAllComments", "true");
        context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);
    }
    // ==============================================================================================jdbc connection
    JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
    jdbcConnectionConfiguration.setDriverClass(databaseConfig.driver());
    jdbcConnectionConfiguration.setConnectionURL(databaseConfig.connectionUrl());
    jdbcConnectionConfiguration.setUserId(databaseConfig.userName.getValue());
    jdbcConnectionConfiguration.setPassword(databaseConfig.password.getValue());
    // 手动添加获取表注释的参数,这里仅找到了这几个数据库的获取方式,如有有获取其他数据库表注释的方法请提issue
    switch(DatabaseType.valueOf(databaseConfig.databaseType.get())) {
        case MySQL:
            // 获取Mysql的表注释
            jdbcConnectionConfiguration.addProperty("useInformationSchema", "true");
            break;
        case Oracle:
        case Oracle_SID:
        case Oracle_ServiceName:
        case Oracle_TNSEntryString:
        case Oracle_TNSName:
            // 获取Oracle的表注释
            jdbcConnectionConfiguration.addProperty("remarksReporting", "true");
            break;
        default:
            jdbcConnectionConfiguration.addProperty("remarksReporting", "true");
            jdbcConnectionConfiguration.addProperty("useInformationSchema", "true");
            break;
    }
    context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
    // =============================================================================================javaTypeResolver
    JavaTypeResolverConfiguration javaTypeResolverConfiguration = new JavaTypeResolverConfiguration();
    javaTypeResolverConfiguration.addProperty("forceBigDecimals", "false");
    context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration);
    // ========================================================================================================model
    JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
    javaModelGeneratorConfiguration.setTargetPackage(projectConfig.entityPackage.getValue().replace(" ", ""));
    javaModelGeneratorConfiguration.setTargetProject(projectDir() + projectConfig.entityDir.getValue());
    javaModelGeneratorConfiguration.addProperty("enableSubPackages", "true");
    javaModelGeneratorConfiguration.addProperty("useActualColumnNames", projectConfig.useActualColumnNames.getValue().toString());
    javaModelGeneratorConfiguration.addProperty("trimStrings", projectConfig.trimStrings.getValue().toString());
    if (!projectConfig.entityRootClass.getValue().isEmpty())
        javaModelGeneratorConfiguration.addProperty("rootClass", projectConfig.entityRootClass.getValue());
    context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
    // =======================================================================================================mapper
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
    sqlMapGeneratorConfiguration.setTargetProject(projectDir() + projectConfig.mapperDir.getValue());
    sqlMapGeneratorConfiguration.setTargetPackage(projectConfig.mapperPackage.getValue());
    sqlMapGeneratorConfiguration.addProperty("useActualColumnNames", projectConfig.useActualColumnNames.getValue().toString());
    sqlMapGeneratorConfiguration.addProperty("enableSubPackages", "true");
    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
    // ==========================================================================================================dao
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
    javaClientGeneratorConfiguration.setConfigurationType(projectConfig.javaClientMapperType.getValue());
    javaClientGeneratorConfiguration.setTargetProject(projectDir() + projectConfig.daoDir.getValue());
    javaClientGeneratorConfiguration.setTargetPackage(projectConfig.daoPackage.getValue());
    sqlMapGeneratorConfiguration.addProperty("useActualColumnNames", projectConfig.useActualColumnNames.getValue().toString());
    sqlMapGeneratorConfiguration.addProperty("enableSubPackages", "true");
    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    // ========================================================================================================table
    TableConfiguration tableConfiguration = new TableConfiguration(context);
    tableConfiguration.setCatalog(databaseConfig.catalog());
    tableConfiguration.setSchema(databaseConfig.schema());
    tableConfiguration.setTableName(projectConfig.selectedTable.getValue());
    tableConfiguration.setDomainObjectName(projectConfig.entityObjName.getValue().replace(" ", ""));
    tableConfiguration.setMapperName(projectConfig.daoObjName.getValue().replace(" ", ""));
    tableConfiguration.setInsertStatementEnabled(projectConfig.enableInsert.getValue());
    tableConfiguration.setSelectByPrimaryKeyStatementEnabled(projectConfig.enableSelectByPrimaryKey.getValue());
    tableConfiguration.setSelectByExampleStatementEnabled(projectConfig.enableSelectByExample.getValue());
    if (projectConfig.selectByPrimaryKeyQueryId.getValue().isEmpty())
        tableConfiguration.setSelectByPrimaryKeyQueryId(projectConfig.selectByPrimaryKeyQueryId.getValue());
    if (!projectConfig.selectByExampleQueryId.getValue().isEmpty())
        tableConfiguration.setSelectByExampleQueryId(projectConfig.selectByExampleQueryId.getValue());
    tableConfiguration.setUpdateByPrimaryKeyStatementEnabled(projectConfig.enableUpdateByPrimaryKey.getValue());
    tableConfiguration.setUpdateByExampleStatementEnabled(projectConfig.enableUpdateByExample.getValue());
    tableConfiguration.setDeleteByPrimaryKeyStatementEnabled(projectConfig.enableDeleteByPrimaryKey.getValue());
    tableConfiguration.setDeleteByExampleStatementEnabled(projectConfig.enableDeleteByExample.getValue());
    tableConfiguration.setCountByExampleStatementEnabled(projectConfig.enableCountByExample.getValue());
    // 使用小骆驼峰替代原列名
    tableConfiguration.addProperty("useActualColumnNames", projectConfig.useActualColumnNames.getValue().toString());
    // 使用小骆驼峰替代原列名
    tableConfiguration.addProperty("ignoreQualifiersAtRuntime", "true");
    Optional.of(projectConfig.tableAlias).filter(notEmptyStringPropertyPredicate).ifPresent((tableAlias) -> {
        tableConfiguration.setAlias(tableAlias.getValue());
    });
    if (!projectConfig.enableVirtualPrimaryKeyPlugin.getValue().isEmpty())
        tableConfiguration.addProperty("virtualKeyColumns", projectConfig.enableVirtualPrimaryKeyPlugin.getValue());
    // see http://www.mybatis.org/generator/configreference/generatedKey.html  ,JDBC is a database independent method of obtaining the value from identity columns,only for Mybatis3+
    if (!projectConfig.primaryKey.getValue().isEmpty()) {
        String sqlStatement = DatabaseType.valueOf(databaseConfig.databaseType.getValue()).getSqlStatement();
        if (// 如果指定了获取自增主键的sql,则覆盖默认的配置
        !projectConfig.lastInsertIdSqlStatement.getValue().trim().isEmpty())
            sqlStatement = projectConfig.lastInsertIdSqlStatement.getValue();
        tableConfiguration.setGeneratedKey(new GeneratedKey(projectConfig.primaryKey.getValue(), sqlStatement, true, null));
    }
    // 添加忽略列/列覆写
    for (TableColumnMetaData column : databaseConfig.tableConfigs.get(projectConfig.selectedTable.getValue())) {
        if (!column.getChecked()) {
            log.info("忽略列:{}", column.getColumnName());
            tableConfiguration.addIgnoredColumn(new IgnoredColumn(column.getColumnName()));
        } else {
            ColumnOverride columnOverride = new ColumnOverride(column.getColumnName());
            columnOverride.setJavaProperty(column.getPropertyName());
            columnOverride.setJavaType(column.getJavaType());
            // columnOverride.setJdbcType(column.getJdbcType());
            columnOverride.setTypeHandler(column.getTypeHandler());
            tableConfiguration.addColumnOverride(columnOverride);
        }
    }
    context.addTableConfiguration(tableConfiguration);
    if (!projectConfig.autoDelimitKeywords.getValue().trim().isEmpty()) {
        context.addProperty("autoDelimitKeywords", "true");
        context.addProperty("beginningDelimiter", projectConfig.autoDelimitKeywords.getValue());
        context.addProperty("endingDelimiter", projectConfig.autoDelimitKeywords.getValue());
        tableConfiguration.setDelimitIdentifiers(true);
    // tableConfiguration.setAllColumnDelimitingEnabled(true);//将此行取消注释即可delimit所有字段
    }
    config.addContext(context);
    List<String> warnings = new ArrayList<>();
    MyShellCallback callback = new MyShellCallback(projectConfig.overwrite.getValue());
    try {
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    } catch (InvalidConfigurationException | InterruptedException | SQLException | IOException e) {
        e.printStackTrace();
    }
    StringBuilder w = new StringBuilder();
    for (String warning : warnings) {
        w.append(warning).append("\n");
    }
    return w.toString();
}
Also used : SQLException(java.sql.SQLException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) TableColumnMetaData(com.spawpaw.mybatis.generator.gui.entity.TableColumnMetaData) IOException(java.io.IOException) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Aggregations

InvalidConfigurationException (org.mybatis.generator.exception.InvalidConfigurationException)12 ArrayList (java.util.ArrayList)11 MyBatisGenerator (org.mybatis.generator.api.MyBatisGenerator)11 Configuration (org.mybatis.generator.config.Configuration)11 ConfigurationParser (org.mybatis.generator.config.xml.ConfigurationParser)9 IOException (java.io.IOException)8 SQLException (java.sql.SQLException)8 DefaultShellCallback (org.mybatis.generator.internal.DefaultShellCallback)8 XMLParserException (org.mybatis.generator.exception.XMLParserException)7 File (java.io.File)5 ConnectionFactoryConfiguration (org.mybatis.generator.config.ConnectionFactoryConfiguration)4 JDBCConnectionConfiguration (org.mybatis.generator.config.JDBCConnectionConfiguration)4 HashSet (java.util.HashSet)3 StringTokenizer (java.util.StringTokenizer)3 Test (org.junit.jupiter.api.Test)3 Properties (java.util.Properties)2 BuildException (org.apache.tools.ant.BuildException)2 SubMonitor (org.eclipse.core.runtime.SubMonitor)2 Context (org.mybatis.generator.config.Context)2 EclipseProgressCallback (org.mybatis.generator.eclipse.core.callback.EclipseProgressCallback)2