我上一个问题的后续问题:Generate an SQL DB creation script with Hibernate 4
目标是让命令行工具能够生成具有给定持久性单元的 SQL 模式的文件(类似于 Hibernate 工具中的 hibernatetool-hbm2ddl Ant 任务)。
根据我之前问题的答案,这可以通过org.hibernate.tool.hbm2ddl.SchemaExport
.
我不想将所有实体添加到Configuration
(如上一个答案中所建议的)我想指定一个PersistenceUnit
.
是否可以将持久性单元添加到 Hibernate Configuration
?
就像是
Properties properties = new Properties();
properties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
...
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory( "persistentUnitName", properties );
Configuration configuration = new Configuration();
... missing part ...
SchemaExport schemaExport = new SchemaExport( configuration );
schemaExport.setOutputFile( "schema.sql" );
...
根据评论中的要求编辑示例persistence.xml
。每个类都有注释@Entity
<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_1_0.xsd"
version="1.0"
>
<persistence-unit
name="doiPersistenceUnit"
transaction-type="JTA"
>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/doi</jta-data-source>
<class>ch.ethz.id.wai.doi.bo.Doi</class>
[...]
<class>ch.ethz.id.wai.doi.bo.DoiPool</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.connection.characterEncoding" value="utf8" />
<property name="hibernate.connection.charSet" value="utf8" />
</properties>
</persistence-unit>
</persistence>