【问题标题】:Is there any command line tool that can generate Java entity classes from db (NOT Netbeans or Eclipse wizard)是否有任何命令行工具可以从 db 生成 Java 实体类(不是 Netbeans 或 Eclipse 向导)
【发布时间】:2011-08-23 18:42:49
【问题描述】:

我曾经使用 Netbeans 向导(版本 6.7.1)从数据库生成实体类。现在我想寻找一个可以完成相同任务的独立工具(脚本、命令行工具...),因为我团队中的一些开发人员使用 Eclipse 而不是 Netbeans,或者使用不同版本的 Netbeans(即 6.9.1 或7.0...),并且那些 IDE 以不同的方式生成实体类。

到目前为止,我还没有找到任何这样的独立工具。也许我错过了一些东西。如果你知道一个,请告诉我。我非常感谢。

【问题讨论】:

  • 由于任务如此之小且定义明确,当然很少有工具可以做到这一点。许多巨大的、昂贵的工具都有一个选项/程序/向导来做同样的事情。但我发现编写 30 到 50 行 Perl 实际上比找到一个完全按照您想要的方式执行它的工具要快得多。由于您的同事已经无法就工具达成一致,也许编写您自己的小型、适应性强的脚本是可行的方法。

标签: java command-line entity dao


【解决方案1】:

您可以使用 Telosys 代码生成器的 CLI(命令行界面)版本

http://www.telosys.org/cli.html

此工具可与任何类型的 IDE 结合使用

【讨论】:

    【解决方案2】:

    我发现自己也遇到了类似的情况,经过一段时间的搜索,我发现命令行中唯一支持此功能的工具是Apache OpenJPA

    需要进行一些配置才能使其工作,但它似乎可以完成这项工作。 它的工作原理是这样的:

    1. 使用Schema Tool 从现有的数据库架构创建一个 .xml 文件。
    2. 可以根据自己的喜好编辑生成的 xml(我通过 Gradle 任务运行整个过程,因此我使用 Groovy 从架构中删除了一些不需要的表)
    3. 使用反向映射工具从 .xml 生成 JPA 实体类(没有足够的声誉发布超过 2 个链接,抱歉)。此工具还可以采用一个可选的定制器类,您可以使用它来进一步定制生成的代码。

    尽管这些工具的文档声明在类路径中拥有一个 properties.xml 文件就足以使它们工作,但对我来说,它们只有在我明确地将它们指向带有“-properties”参数的文件时才有效.

    这里有一些代码 sn-ps 可以节省任何人阅读本文的时间。这是使用 OpenJPA 2.3.0 测试的:

    生成模式 xml(在我的例子中来自 MSSQL DB,因此驱动程序位于类路径中):

    java -cp openjpa-all-2.3.0.jar;sqljdbc4.jar org.apache.openjpa.jdbc.schema.SchemaTool -properties openjpa.xml -action reflect -file schema.xml
    

    从 xml 生成实体

    java -cp openjpa-all-2.3.0.jar org.apache.openjpa.jdbc.meta.ReverseMappingTool -properties openjpa.xml -metadata none -annotations true -nullableAsObject true -useGenericCollections true -pkg {your package} -directory {output directory} schema.xml
    

    openjpa.xml 示例(同样,对于 MSSQL DB):

    <?xml version="1.0"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
      <persistence-unit name="Gaya STG">
        <properties>
          <property name="openjpa.ConnectionURL" value="jdbc:sqlserver://{ip}"/>
          <property name="openjpa.ConnectionDriverName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
          <property name="openjpa.ConnectionUserName" value="{username}"/>
          <property name="openjpa.ConnectionPassword" value="{pass}"/>
          <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
        </properties>
      </persistence-unit>
    </persistence>
    

    包含上述所有任务的 build.gradle 示例文件(同样,对于 MSSQL DB):

    import java.util.regex.Pattern
    
    apply plugin: 'java'
    
    dependencies {
        compile "org.apache.openjpa:openjpa-all:2.3.0"
        compile "sqljdbc4:sqljdbc4:sqljdbc4"
    }
    
    task cleanSchemaXml(type: Delete) {
        delete file("schema.xml")
    }
    
    task generateSchemaXml(type: JavaExec, dependsOn: cleanSchemaXml) {
        classpath = configurations.compile
        main = "org.apache.openjpa.jdbc.schema.SchemaTool"
        args "-properties", getPropertiesFile(),
             "-action", "reflect",
             "-file", "schema.xml"
    
        doFirst {
            println "Generating schema.xml..."
        }
    
        doLast {
            println "Done generating schema.xml."
            println "Updating schema.xml..."
            updateSchema()
            println "Done updating schema.xml."
        }
    }
    
    task cleanEntities(type: Delete) {
        delete fileTree(dir: "{path/to/your/entities}")
    }
    
    task generateEntities(type: JavaExec, dependsOn: [cleanEntities, clean,  generateSchemaXml, jar]) {
        classpath = files(configurations.compile, jar.archivePath)  // Add this module's jar to the executed classpath, so we can use the EntityCustomizer (which is assumed to be in this module).
        main = "org.apache.openjpa.jdbc.meta.ReverseMappingTool"
        args "-metadata", "none",
             "-annotations", "true",
             "-nullableAsObject", "true",
             "-useGenericCollections", "true",
             "-properties", getPropertiesFile(),
    //        "-customizerClass", "{path.to.your.EntityCustomizer}",
             "-directory", "{path/to/your/entities}",
             "-pkg", "{your.entity.package}",
             "schema.xml"
    
        doFirst {
            println "Generating entity classes from schema.xml..."
        }
    
        doLast {
            println "Done generating entity classes."
        }
    }
    
    private String getPropertiesFile() {
        // File is read directly from the file-system, will not work from a Jar.
        return file("src/main/resources/openjpa.xml").getAbsolutePath()
    }
    
    private void updateSchema() {
        // Only this schema will be kept.
        final def schemasToKeep = ['dbo']
    
        // These tables will be removed from the .xml
        final def tablesToRemove = [
            'ReplicationMonitor', 'DDLEvents', 'AuditTrail', 'AuditTrailErrorLog', 'sysdiagrams', 'table_relations',
            'tasks_queue', 'tasks_queue_archive',
            '.*history'    // Remove all tables ending with 'history'.
        ].collect { Pattern.compile(it) }
    
        final File xmlFile = file('schema.xml')
    
        // Read xml.
        final def xml = new XmlParser().parse(xmlFile)
    
        // Remove all unnecessary schemas.
        filterSchemas(xml, schemasToKeep)
    
        // Remove all unnecessary tables.
        filterTables(xml, tablesToRemove)
    
        // Save updated xml file.
        new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)
    }
    
    private void filterSchemas(Node xml, List<String> schemasToKeep) {
        final List<Node> removedSchemas = []
        xml.each { schema ->
            final String name = schema.@name
            if (!schemasToKeep.contains(name)) {
                println("Removing schema: $name")
                removedSchemas += schema
            }
        }
        removedSchemas.each { xml.remove(it) }
    }
    
    private void filterTables(Node xml, List<Pattern> tablesToRemove) {
        xml.each { schema ->
            final List<Node> removedTables = []
            schema.each { table ->
                final String name = table.@name
                if (tablesToRemove.any { it.matcher(name).matches() }) {
                    println("Removing table: $name")
                    removedTables += table
                }
            }
            removedTables.each { schema.remove(it) }
        }
    }
    

    【讨论】:

      【解决方案3】:

      Eclipse 用户,您应该使用 Eclipse 插件,例如“Telosys Tools” (http://marketplace.eclipse.org/content/telosys-tools)

      它做你想做的事:连接到数据库,检索架构并 生成任何类型的源文件,如 JPA 实体 看教程:https://sites.google.com/site/telosystutorial/

      JPA 模板在这里:https://github.com/telosys-tools/persistence-jpa-TT210-R2

      【讨论】:

      【解决方案4】:

      试试 Hibernate 的 hbm2ddl:

      http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

      查找hibernate.hbm2ddl.auto 参数。它有一个创建选项。

      【讨论】:

      • 据我了解,设置 hibernate.hbm2ddl.auto=create 是为了生成数据库模式。我仍然没有看到您的解决方案与我的问题之间的关系。可以说清楚一点吗?
      • 楼主反问
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多