Search in sources :

Example 1 with MyBatisGenerator

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

the class MyBatisGeneratorTest method testGenerateIbatis2WithInvalidConfig.

@Test(expected = InvalidConfigurationException.class)
public void testGenerateIbatis2WithInvalidConfig() throws Exception {
    List<String> warnings = new ArrayList<String>();
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(this.getClass().getClassLoader().getResourceAsStream("generatorConfigIbatis2_badConfig.xml"));
    DefaultShellCallback shellCallback = new DefaultShellCallback(true);
    try {
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, shellCallback, warnings);
        myBatisGenerator.generate(null, null, null, false);
    } catch (InvalidConfigurationException e) {
        assertEquals(1, e.getErrors().size());
        throw e;
    }
}
Also used : Configuration(org.mybatis.generator.config.Configuration) ConnectionFactoryConfiguration(org.mybatis.generator.config.ConnectionFactoryConfiguration) JDBCConnectionConfiguration(org.mybatis.generator.config.JDBCConnectionConfiguration) ArrayList(java.util.ArrayList) ConfigurationParser(org.mybatis.generator.config.xml.ConfigurationParser) DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) Test(org.junit.Test)

Example 2 with MyBatisGenerator

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

the class CodeGenerator method genModelAndMapper.

public static void genModelAndMapper(String tableName, String modelName) {
    Context context = new Context(ModelType.FLAT);
    context.setId("Potato");
    context.setTargetRuntime("MyBatis3Simple");
    context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
    context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
    JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
    jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
    jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
    jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
    jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
    context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
    PluginConfiguration pluginConfiguration = new PluginConfiguration();
    pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
    pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE);
    // pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
    context.addPluginConfiguration(pluginConfiguration);
    JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
    javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
    javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE + "." + tableName);
    context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
    sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
    sqlMapGeneratorConfiguration.setTargetPackage("mapper");
    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
    javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
    javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE);
    javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    TableConfiguration tableConfiguration = new TableConfiguration(context);
    tableConfiguration.setTableName(tableName);
    if (StringUtils.isNotEmpty(modelName))
        tableConfiguration.setDomainObjectName(modelName);
    tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
    context.addTableConfiguration(tableConfiguration);
    List<String> warnings;
    MyBatisGenerator generator;
    try {
        Configuration config = new Configuration();
        config.addContext(context);
        config.validate();
        boolean overwrite = true;
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        warnings = new ArrayList<String>();
        generator = new MyBatisGenerator(config, callback, warnings);
        generator.generate(null);
    } catch (Exception e) {
        throw new RuntimeException("生成Model和Mapper失败", e);
    }
    if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
        throw new RuntimeException("生成Model和Mapper失败:" + warnings);
    }
    if (StringUtils.isEmpty(modelName))
        modelName = tableNameConvertUpperCamel(tableName);
    System.out.println(modelName + ".java 生成成功");
    System.out.println(modelName + "Mapper.java 生成成功");
    System.out.println(modelName + "Mapper.xml 生成成功");
}
Also used : DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) IOException(java.io.IOException) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 3 with MyBatisGenerator

use of org.mybatis.generator.api.MyBatisGenerator 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 MybatisDefaultShellCallback(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) MybatisDefaultShellCallback(com.luastar.swift.tools.func.mybatis.ext.MybatisDefaultShellCallback) ShellCallback(org.mybatis.generator.api.ShellCallback) ArrayList(java.util.ArrayList) MybatisDefaultShellCallback(com.luastar.swift.tools.func.mybatis.ext.MybatisDefaultShellCallback) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 4 with MyBatisGenerator

use of org.mybatis.generator.api.MyBatisGenerator in project paascloud-master by paascloud.

the class MybatisGenerator method main.

/**
 * The entry point of application.
 *
 * @param args the input arguments
 *
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    List<String> warnings = new ArrayList<>();
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(Generator.class.getResourceAsStream("/generator/generatorConfig.xml"));
    DefaultShellCallback callback = new DefaultShellCallback(true);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
}
Also used : Configuration(org.mybatis.generator.config.Configuration) ArrayList(java.util.ArrayList) ConfigurationParser(org.mybatis.generator.config.xml.ConfigurationParser) DefaultShellCallback(org.mybatis.generator.internal.DefaultShellCallback) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator) Generator(com.sun.tools.corba.se.idl.Generator) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 5 with MyBatisGenerator

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

Aggregations

MyBatisGenerator (org.mybatis.generator.api.MyBatisGenerator)29 ArrayList (java.util.ArrayList)25 DefaultShellCallback (org.mybatis.generator.internal.DefaultShellCallback)24 Configuration (org.mybatis.generator.config.Configuration)23 ConfigurationParser (org.mybatis.generator.config.xml.ConfigurationParser)22 File (java.io.File)13 InvalidConfigurationException (org.mybatis.generator.exception.InvalidConfigurationException)11 IOException (java.io.IOException)9 SQLException (java.sql.SQLException)7 XMLParserException (org.mybatis.generator.exception.XMLParserException)6 ConnectionFactoryConfiguration (org.mybatis.generator.config.ConnectionFactoryConfiguration)4 JDBCConnectionConfiguration (org.mybatis.generator.config.JDBCConnectionConfiguration)4 HashSet (java.util.HashSet)3 Test (org.junit.jupiter.api.Test)3 ShellCallback (org.mybatis.generator.api.ShellCallback)3 Properties (java.util.Properties)2 StringTokenizer (java.util.StringTokenizer)2 BuildException (org.apache.tools.ant.BuildException)2 SubMonitor (org.eclipse.core.runtime.SubMonitor)2 Test (org.junit.Test)2