Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.tool.hbm2ddl.SchemaExport and PostgreSQL

I am using org.hibernate.tool.hbm2ddl.SchemaExport to generate an SQL script for DB creation on PostgreSQL.

Simplified example:

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 );

The generated schema looks like that

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;

The problem is that if the database is empty the first series of command (ALTER TABLE) will fail as they make sense only if the table exists. PostgreSQL then performs a complete roll back and nothing is created.

This happens only for the constraints: for the table the DROP statement is correctly enhanced with IF EXISTS

Is this an Hibernate bug or am I doing something wrong?

like image 564
Matteo Avatar asked Mar 17 '26 02:03

Matteo


1 Answers

Instead of

schemaExport.create( true, false );

call

schemaExport.execute(true, false, false, true)

It will create DDL without alter/drop statements

(see javadoc for details http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/tool/hbm2ddl/SchemaExport.html)

like image 125
František Hartman Avatar answered Mar 19 '26 16:03

František Hartman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!