是否有gradle插件或其他任何调用hibernate-tools hbm2ddl任务的方法,以便从带注释的类生成数据库架构,而不必在某个配置文件中列出所有实体(@Entity),但可以在类路径中找到它们?
最好是休眠5,但休眠4也可以。
最佳答案
我终于通过移动persistence.xml文件实现了这一目标。
在我的场景中,我有一些库实体和一些应用程序实体,我想为其生成架构。显然,我需要在persistence.xml中列出库实体,这很好,因为它们不会经常更改,但是为了使应用程序实体从类路径中拾取而不在持久性文件中列出它们,我必须确保类和persistence.xml文件都由同一类加载器加载(我想)。
这是可行的。
库实体:MyCustomer,MyInvoice
应用程序实体:MyBook,MyBooking
/src/main/resources/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="defaultPersistenceUnit">
<!-- List the library classes only -->
<class>net.mylibrary.entity.MyCustomer</class>
<class>net.mylibrary.entity.MyInvoice</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="myusr"/>
<property name="hibernate.connection.password" value="mypwd"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/mydb"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
</properties>
</persistence-unit>
</persistence>
build.gradle:
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
repositories {
jcenter()
mavenLocal()
}
dependencies {
compile ... my project dependencies ...
}
configurations {
hibtools
}
dependencies {
hibtools 'net.mylibrary:MyEntities:1.0' // Library for MyCustomer and MyInvoice
hibtools 'org.hibernate:hibernate-tools:4.+',
'mysql:mysql-connector-java:5.+'
hibtools files("$buildDir/classes/main") // MyBook and MyBooking
}
task createSchema(dependsOn: ['build', 'copyPersistenceUnit']) << {
ant.taskdef(name: 'hibernatetool',
classname: 'org.hibernate.tool.ant.HibernateToolTask',
classpath: configurations.hibtools.asPath)
ant.hibernatetool(destdir: 'schema') {
ant.jpaconfiguration(persistenceunit: 'defaultPersistenceUnit')
ant.hbm2ddl(drop: 'false', export: 'false', outputfilename: 'mydb.sql')
}
}
task copyPersistenceUnit(type: Copy) {
from "$buildDir/resources/main/META-INF/persistence.xml"
into "$buildDir/classes/main/META-INF/"
}
结果是一个ddl,其中包含MyCustomer,MyInvoice,MyBook,MyBooking的表,即使MyBook和MyBooking不在任何地方,也可以在不更改配置的情况下添加或删除。
这里的技巧是将persistence.xml文件从resources文件夹复制到classes文件夹。
如果不这样做,则为了找到它,您需要使用以下方法将资源路径添加到hibtools配置:
hibtools files(["$buildDir/resources/main", "$buildDir/classes/main"])
但是这样做会阻止您的应用程序实体被发现。
这适用于Hibernate4。使用当前的Hibernate 5 alpha工具将提供一个空的ddl文件。
关于hibernate - 从gradle调用hbm2ddl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228135/