N. *_*. P 11 java command-line entity dao
我曾经使用Netbeans向导(版本6.7.1)从数据库生成实体类.现在我想寻找一个可以完成相同任务的独立工具(脚本,命令行工具......),因为我团队中的一些开发人员使用的是Eclipse而不是Netbeans,或者使用不同版本的Netbeans(即6.9.1或7.0 ...),那些IDE以不同的方式生成实体类.
到目前为止,我还没有找到任何类似的独立工具.也许我错过了什么.如果你知道一个,请告诉我.我非常感激.
我发现自己处于类似的情况,经过一段时间的搜索后,我发现唯一支持从命令行执行此操作的工具是Apache OpenJPA。
需要一些配置才能使其工作,但它似乎可以完成工作。它的工作原理如下:
尽管这些工具的文档指出,在类路径上有一个properties.xml 文件就足以使它们工作,但对我来说,只有当我明确地将它们指向带有“-properties”参数的文件时,它们才起作用。
这里有一些代码片段,可以帮助任何人节省阅读本文的时间。这是使用 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
Run Code Online (Sandbox Code Playgroud)
从 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
Run Code Online (Sandbox Code Playgroud)
示例 openjpa.xml(同样适用于 MSSQL 数据库):
<?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>
Run Code Online (Sandbox Code Playgroud)
包含上述所有任务的示例 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) }
}
}
Run Code Online (Sandbox Code Playgroud)
duf*_*ymo -1
尝试 Hibernate 的 hbm2ddl:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
寻找hibernate.hbm2ddl.auto参数。它有一个创建选项。
| 归档时间: |
|
| 查看次数: |
4132 次 |
| 最近记录: |