Search in sources :

Example 11 with MyBatisGenerator

use of org.mybatis.generator.api.MyBatisGenerator in project generator by mybatis.

the class GeneratorAntTask method execute.

/*
     * (non-Javadoc)
     * 
     * @see org.apache.tools.ant.Task#execute()
     */
@Override
public void execute() throws BuildException {
    if (!stringHasValue(configfile)) {
        //$NON-NLS-1$
        throw new BuildException(getString("RuntimeError.0"));
    }
    List<String> warnings = new ArrayList<String>();
    File configurationFile = new File(configfile);
    if (!configurationFile.exists()) {
        throw new BuildException(getString("RuntimeError.1", //$NON-NLS-1$
        configfile));
    }
    Set<String> fullyqualifiedTables = new HashSet<String>();
    if (stringHasValue(fullyQualifiedTableNames)) {
        StringTokenizer st = new StringTokenizer(fullyQualifiedTableNames, //$NON-NLS-1$
        ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                fullyqualifiedTables.add(s);
            }
        }
    }
    Set<String> contexts = new HashSet<String>();
    if (stringHasValue(contextIds)) {
        //$NON-NLS-1$
        StringTokenizer st = new StringTokenizer(contextIds, ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                contexts.add(s);
            }
        }
    }
    try {
        Properties p = propertyset == null ? null : propertyset.getProperties();
        ConfigurationParser cp = new ConfigurationParser(p, warnings);
        Configuration config = cp.parseConfiguration(configurationFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(new AntProgressCallback(this, verbose), contexts, fullyqualifiedTables);
    } catch (XMLParserException e) {
        for (String error : e.getErrors()) {
            log(error, Project.MSG_ERR);
        }
        throw new BuildException(e.getMessage());
    } catch (SQLException e) {
        throw new BuildException(e.getMessage());
    } catch (IOException e) {
        throw new BuildException(e.getMessage());
    } catch (InvalidConfigurationException e) {
        for (String error : e.getErrors()) {
            log(error, Project.MSG_ERR);
        }
        throw new BuildException(e.getMessage());
    } catch (InterruptedException e) {
    // ignore (will never happen with the DefaultShellCallback)
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException(e.getMessage());
    }
    for (String error : warnings) {
        log(error, Project.MSG_WARN);
    }
}
Also used : Configuration(org.mybatis.generator.config.Configuration) XMLParserException(org.mybatis.generator.exception.XMLParserException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Messages.getString(org.mybatis.generator.internal.util.messages.Messages.getString) DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) SQLException(java.sql.SQLException) XMLParserException(org.mybatis.generator.exception.XMLParserException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) StringTokenizer(java.util.StringTokenizer) ConfigurationParser(org.mybatis.generator.config.xml.ConfigurationParser) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) HashSet(java.util.HashSet) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 12 with MyBatisGenerator

use of org.mybatis.generator.api.MyBatisGenerator in project mybatis-generator-gui-extension by spawpaw.

the class MBGRunner method generate.

public String generate() {
    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());
    // =====================================================================================================加载插件
    // initialize plugin data
    initPluginConfigs();
    addPlugins();
    // ====================================================================================================注释生成器
    if (projectConfig.enableComment.getValue()) {
        CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
        commentGeneratorConfiguration.setConfigurationType(DeclaredPlugins.CommentPlugin);
        // commentGeneratorConfiguration.addProperty("suppressAllComments", "true");
        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);
    }
    // ==============================================================================================jdbc connection
    JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
    jdbcConnectionConfiguration.setDriverClass(databaseConfig.driver());
    jdbcConnectionConfiguration.setConnectionURL(databaseConfig.connectionUrl());
    jdbcConnectionConfiguration.setUserId(databaseConfig.userName.getValue());
    jdbcConnectionConfiguration.setPassword(databaseConfig.password.getValue());
    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", "true");
    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.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());
    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())
        tableConfiguration.setGeneratedKey(new GeneratedKey(projectConfig.primaryKey.getValue(), "JDBC", true, null));
    // 添加忽略列/列覆写
    for (TableColumnMetaData column : databaseConfig.tableConfigs.get(projectConfig.selectedTable.getValue())) {
        if (!column.getChecked()) {
            System.out.println("忽略的列:" + 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);
    config.addContext(context);
    List<String> warnings = new ArrayList<>();
    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    try {
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    } catch (InvalidConfigurationException | InterruptedException | SQLException | IOException e) {
        e.printStackTrace();
    }
    return warnings.toString();
}
Also used : SQLException(java.sql.SQLException) DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) IOException(java.io.IOException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) TableColumnMetaData(com.spawpaw.mybatis.generator.gui.entity.TableColumnMetaData) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Aggregations

MyBatisGenerator (org.mybatis.generator.api.MyBatisGenerator)12 ArrayList (java.util.ArrayList)11 Configuration (org.mybatis.generator.config.Configuration)11 ConfigurationParser (org.mybatis.generator.config.xml.ConfigurationParser)9 InvalidConfigurationException (org.mybatis.generator.exception.InvalidConfigurationException)9 DefaultShellCallback (org.mybatis.generator.internal.DefaultShellCallback)9 IOException (java.io.IOException)5 SQLException (java.sql.SQLException)5 Test (org.junit.Test)4 ConnectionFactoryConfiguration (org.mybatis.generator.config.ConnectionFactoryConfiguration)4 JDBCConnectionConfiguration (org.mybatis.generator.config.JDBCConnectionConfiguration)4 XMLParserException (org.mybatis.generator.exception.XMLParserException)4 HashSet (java.util.HashSet)3 StringTokenizer (java.util.StringTokenizer)3 File (java.io.File)2 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