我发现自己也遇到了类似的情况,经过一段时间的搜索,我发现命令行中唯一支持此功能的工具是Apache OpenJPA。
需要进行一些配置才能使其工作,但它似乎可以完成这项工作。
它的工作原理是这样的:
- 使用Schema Tool 从现有的数据库架构创建一个 .xml 文件。
- 可以根据自己的喜好编辑生成的 xml(我通过 Gradle 任务运行整个过程,因此我使用 Groovy 从架构中删除了一些不需要的表)
- 使用反向映射工具从 .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) }
}
}