【发布时间】:2012-12-19 02:59:27
【问题描述】:
我上一个问题的后续问题:Generate an SQL DB creation script with Hibernate 4
目标是让命令行工具能够生成具有给定持久性单元的 SQL 模式的文件(类似于 Hibernate 工具中的 hibernatetool-hbm2ddl Ant 任务)。
根据我上一个问题的答案,这可以通过org.hibernate.tool.hbm2ddl.SchemaExport 来实现。
我想指定一个PersistenceUnit,而不是将所有实体添加到Configuration(如上一个答案中所建议的)。
是否可以添加一个持久化单元到 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" );
...
编辑根据 cmets 中的要求,一个示例 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>
【问题讨论】:
-
所以你想保存
config.addAnnotatedClass(MyMappedPojo1.class);行? -
@yair 是的,我想避免手动指定所有类(并避免对它们进行硬编码)。我知道我可以解析 persistence.xml 文件,但我怀疑有更简单的方法。
-
我认为您还缺少将方言传递到配置中 - 创建 SchemaExport 时它将失败。
标签: java hibernate persistence-unit