我正在使用 org.hibernate.tool.hbm2ddl.SchemaExport
生成用于在 PostgreSQL 上创建数据库的 SQL 脚本。
简化示例:
Properties entityManagerFactoryProperties = new Properties();
entityManagerFactoryProperties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
[…]
Configuration configuration = new Configuration();
configuration.setProperty( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( persistenceUnitName, entityManagerFactoryProperties );
Metamodel metamodel = entityManagerFactory.getMetamodel();
for ( final ManagedType< ? > managedType : metamodel.getManagedTypes() ) {
Class< ? > entityClass = managedType.getJavaType();
configuration.addAnnotatedClass( entityClass );
}
SchemaExport schemaExport = new SchemaExport( configuration );
schemaExport.setOutputFile( schemaFile );
schemaExport.setFormat( true );
schemaExport.setDelimiter( ";" );
schemaExport.create( true, false );
生成的模式看起来像这样
alter table TableName
drop constraint FK101841AFEA9FC;
[…]
drop table if exists TableName cascade;
[…]
create table TableName (
dbId int8 not null,
[…]
compositeSingle_dbId int8,
primary key (dbId)
);
alter table TableName
add constraint FK101841AFEA9FC
foreign key (compositeSingle_dbId)
references TableName2;
问题是,如果数据库为空,第一系列命令 (ALTER TABLE
) 将失败,因为它们只有在表存在时才有意义。然后 PostgreSQL 执行完全回滚并且没有创建任何内容。
这仅发生在约束条件下:对于表,DROP
语句已使用 IF EXISTS
正确增强
这是 Hibernate 错误还是我做错了什么?
最佳答案
代替
schemaExport.create( true, false );
打电话
schemaExport.execute(true, false, false, true)
它将创建没有 alter/drop 语句的 DDL
(有关详细信息,请参阅 javadoc http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/tool/hbm2ddl/SchemaExport.html)
关于hibernate - org.hibernate.tool.hbm2ddl.SchemaExport 和 PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14314733/