Search in sources :

Example 1 with ShellCallback

use of org.mybatis.generator.api.ShellCallback in project mybatis-generator-gui by zouzg.

the class MybatisGeneratorBridge method generate.

public void generate() throws Exception {
    Configuration configuration = new Configuration();
    Context context = new Context(ModelType.CONDITIONAL);
    configuration.addContext(context);
    context.addProperty("javaFileEncoding", "UTF-8");
    String connectorLibPath = ConfigHelper.findConnectorLibPath(selectedDatabaseConfig.getDbType());
    _LOG.info("connectorLibPath: {}", connectorLibPath);
    configuration.addClasspathEntry(connectorLibPath);
    // Table configuration
    TableConfiguration tableConfig = new TableConfiguration(context);
    tableConfig.setTableName(generatorConfig.getTableName());
    tableConfig.setDomainObjectName(generatorConfig.getDomainObjectName());
    if (!generatorConfig.isUseExampe()) {
        tableConfig.setUpdateByExampleStatementEnabled(false);
        tableConfig.setCountByExampleStatementEnabled(false);
        tableConfig.setDeleteByExampleStatementEnabled(false);
        tableConfig.setSelectByExampleStatementEnabled(false);
    }
    if (DbType.MySQL.name().equals(selectedDatabaseConfig.getDbType())) {
        tableConfig.setSchema(selectedDatabaseConfig.getSchema());
    } else {
        tableConfig.setCatalog(selectedDatabaseConfig.getSchema());
    }
    // 针对 postgresql 单独配置
    if (DbType.valueOf(selectedDatabaseConfig.getDbType()).getDriverClass() == "org.postgresql.Driver") {
        tableConfig.setDelimitIdentifiers(true);
    }
    // 添加GeneratedKey主键生成
    if (StringUtils.isNoneEmpty(generatorConfig.getGenerateKeys())) {
        tableConfig.setGeneratedKey(new GeneratedKey(generatorConfig.getGenerateKeys(), selectedDatabaseConfig.getDbType(), true, null));
    }
    // add ignore columns
    if (ignoredColumns != null) {
        ignoredColumns.stream().forEach(ignoredColumn -> {
            tableConfig.addIgnoredColumn(ignoredColumn);
        });
    }
    if (columnOverrides != null) {
        columnOverrides.stream().forEach(columnOverride -> {
            tableConfig.addColumnOverride(columnOverride);
        });
    }
    if (generatorConfig.isUseActualColumnNames()) {
        tableConfig.addProperty("useActualColumnNames", "true");
    }
    if (generatorConfig.isUseTableNameAlias()) {
        tableConfig.setAlias(generatorConfig.getTableName());
    }
    JDBCConnectionConfiguration jdbcConfig = new JDBCConnectionConfiguration();
    // http://www.mybatis.org/generator/usage/mysql.html
    if (DbType.MySQL.name().equals(selectedDatabaseConfig.getDbType())) {
        jdbcConfig.addProperty("nullCatalogMeansCurrent", "true");
    }
    jdbcConfig.setDriverClass(DbType.valueOf(selectedDatabaseConfig.getDbType()).getDriverClass());
    jdbcConfig.setConnectionURL(DbUtil.getConnectionUrlWithSchema(selectedDatabaseConfig));
    jdbcConfig.setUserId(selectedDatabaseConfig.getUsername());
    jdbcConfig.setPassword(selectedDatabaseConfig.getPassword());
    // java model
    JavaModelGeneratorConfiguration modelConfig = new JavaModelGeneratorConfiguration();
    modelConfig.setTargetPackage(generatorConfig.getModelPackage());
    modelConfig.setTargetProject(generatorConfig.getProjectFolder() + "/" + generatorConfig.getModelPackageTargetFolder());
    // Mapper configuration
    SqlMapGeneratorConfiguration mapperConfig = new SqlMapGeneratorConfiguration();
    mapperConfig.setTargetPackage(generatorConfig.getMappingXMLPackage());
    mapperConfig.setTargetProject(generatorConfig.getProjectFolder() + "/" + generatorConfig.getMappingXMLTargetFolder());
    // DAO
    JavaClientGeneratorConfiguration daoConfig = new JavaClientGeneratorConfiguration();
    daoConfig.setConfigurationType("XMLMAPPER");
    daoConfig.setTargetPackage(generatorConfig.getDaoPackage());
    daoConfig.setTargetProject(generatorConfig.getProjectFolder() + "/" + generatorConfig.getDaoTargetFolder());
    context.setId("myid");
    context.addTableConfiguration(tableConfig);
    context.setJdbcConnectionConfiguration(jdbcConfig);
    context.setJdbcConnectionConfiguration(jdbcConfig);
    context.setJavaModelGeneratorConfiguration(modelConfig);
    context.setSqlMapGeneratorConfiguration(mapperConfig);
    context.setJavaClientGeneratorConfiguration(daoConfig);
    // Comment
    CommentGeneratorConfiguration commentConfig = new CommentGeneratorConfiguration();
    commentConfig.setConfigurationType(DbRemarksCommentGenerator.class.getName());
    if (generatorConfig.isComment()) {
        commentConfig.addProperty("columnRemarks", "true");
    }
    if (generatorConfig.isAnnotation()) {
        commentConfig.addProperty("annotations", "true");
    }
    context.setCommentGeneratorConfiguration(commentConfig);
    // set java file encoding
    context.addProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING, generatorConfig.getEncoding());
    // 实体添加序列化
    PluginConfiguration serializablePluginConfiguration = new PluginConfiguration();
    serializablePluginConfiguration.addProperty("type", "org.mybatis.generator.plugins.SerializablePlugin");
    serializablePluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
    context.addPluginConfiguration(serializablePluginConfiguration);
    // toString, hashCode, equals插件
    if (generatorConfig.isNeedToStringHashcodeEquals()) {
        PluginConfiguration pluginConfiguration1 = new PluginConfiguration();
        pluginConfiguration1.addProperty("type", "org.mybatis.generator.plugins.EqualsHashCodePlugin");
        pluginConfiguration1.setConfigurationType("org.mybatis.generator.plugins.EqualsHashCodePlugin");
        context.addPluginConfiguration(pluginConfiguration1);
        PluginConfiguration pluginConfiguration2 = new PluginConfiguration();
        pluginConfiguration2.addProperty("type", "org.mybatis.generator.plugins.ToStringPlugin");
        pluginConfiguration2.setConfigurationType("org.mybatis.generator.plugins.ToStringPlugin");
        context.addPluginConfiguration(pluginConfiguration2);
    }
    // limit/offset插件
    if (generatorConfig.isOffsetLimit()) {
        if (DbType.MySQL.name().equals(selectedDatabaseConfig.getDbType()) || DbType.PostgreSQL.name().equals(selectedDatabaseConfig.getDbType())) {
            PluginConfiguration pluginConfiguration = new PluginConfiguration();
            pluginConfiguration.addProperty("type", "com.zzg.mybatis.generator.plugins.MySQLLimitPlugin");
            pluginConfiguration.setConfigurationType("com.zzg.mybatis.generator.plugins.MySQLLimitPlugin");
            context.addPluginConfiguration(pluginConfiguration);
        }
    }
    context.setTargetRuntime("MyBatis3");
    List<String> warnings = new ArrayList<>();
    Set<String> fullyqualifiedTables = new HashSet<>();
    Set<String> contexts = new HashSet<>();
    // override=true
    ShellCallback shellCallback = new DefaultShellCallback(true);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, shellCallback, warnings);
    // if overrideXML selected, delete oldXML ang generate new one
    if (generatorConfig.isOverrideXML()) {
        String mappingXMLFilePath = getMappingXMLFilePath(generatorConfig);
        File mappingXMLFile = new File(mappingXMLFilePath);
        if (mappingXMLFile.exists()) {
            mappingXMLFile.delete();
        }
    }
    myBatisGenerator.generate(progressCallback, contexts, fullyqualifiedTables);
}
Also used : DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) ShellCallback(org.mybatis.generator.api.ShellCallback) ArrayList(java.util.ArrayList) DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) DbRemarksCommentGenerator(com.zzg.mybatis.generator.plugins.DbRemarksCommentGenerator) File(java.io.File) HashSet(java.util.HashSet) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 2 with ShellCallback

use of org.mybatis.generator.api.ShellCallback in project swift by luastar.

the class MybatisGen method gen.

public void gen() {
    try {
        Configuration configuration = new Configuration();
        // context
        Context context = new Context(ModelType.FLAT);
        context.setId(RandomUtils.bsonId());
        /*
                MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample;
                MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample;
             */
        context.setTargetRuntime("MyBatis3");
        // 自动识别数据库关键字,默认false,如果设置为true
        context.addProperty("autoDelimitKeywords", "false");
        // 生成的Java文件的编码
        context.addProperty("javaFileEncoding", "UTF-8");
        // 格式化java代码
        context.addProperty("javaFormatter", "org.mybatis.generator.api.dom.DefaultJavaFormatter");
        // 格式化XML代码
        context.addProperty("xmlFormatter", "org.mybatis.generator.api.dom.DefaultXmlFormatter");
        // 指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号;
        context.addProperty("beginningDelimiter", "`");
        context.addProperty("endingDelimiter", "`");
        // plugin
        List<PluginConfiguration> pluginConfigurationList = getPluginConfigurationList();
        for (PluginConfiguration pluginConfiguration : pluginConfigurationList) {
            context.addPluginConfiguration(pluginConfiguration);
        }
        // commentGenerator
        context.setCommentGeneratorConfiguration(getCommentGeneratorConfiguration());
        // jdbcConnection
        context.setJdbcConnectionConfiguration(getJDBCConnectionConfiguration());
        // javaTypeResolver
        context.setJavaTypeResolverConfiguration(getJavaTypeResolverConfiguration());
        // javaModelGenerator
        context.setJavaModelGeneratorConfiguration(getJavaModelGeneratorConfiguration());
        // sqlMapGenerator
        context.setSqlMapGeneratorConfiguration(getSqlMapGeneratorConfiguration());
        // javaClientGenerator
        context.setJavaClientGeneratorConfiguration(getJavaClientGeneratorConfiguration());
        // table
        List<TableConfiguration> tableConfigurationList = getTableConfigurationList(context);
        for (TableConfiguration tableConfiguration : tableConfigurationList) {
            context.addTableConfiguration(tableConfiguration);
        }
        configuration.addContext(context);
        // generate
        ShellCallback shellCallback = new MybatisShellCallback(true);
        List<String> warnings = new ArrayList<String>();
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, shellCallback, warnings);
        myBatisGenerator.generate(new NullProgressCallback());
        logger.info("gen success, see {}", output);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
Also used : NullProgressCallback(org.mybatis.generator.internal.NullProgressCallback) ShellCallback(org.mybatis.generator.api.ShellCallback) ArrayList(java.util.ArrayList) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 3 with ShellCallback

use of org.mybatis.generator.api.ShellCallback 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)

Aggregations

ArrayList (java.util.ArrayList)3 MyBatisGenerator (org.mybatis.generator.api.MyBatisGenerator)3 ShellCallback (org.mybatis.generator.api.ShellCallback)3 HashSet (java.util.HashSet)2 DbRemarksCommentGenerator (com.zzg.mybatis.generator.plugins.DbRemarksCommentGenerator)1 File (java.io.File)1 IOException (java.io.IOException)1 SQLException (java.sql.SQLException)1 StringTokenizer (java.util.StringTokenizer)1 Resource (org.apache.maven.model.Resource)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 Configuration (org.mybatis.generator.config.Configuration)1 ConfigurationParser (org.mybatis.generator.config.xml.ConfigurationParser)1 InvalidConfigurationException (org.mybatis.generator.exception.InvalidConfigurationException)1 XMLParserException (org.mybatis.generator.exception.XMLParserException)1 DefaultShellCallback (org.mybatis.generator.internal.DefaultShellCallback)1 NullProgressCallback (org.mybatis.generator.internal.NullProgressCallback)1