Run code after Hibernate updates database schema?
Is there a way to register some kind of SchemaExportEventListener (that's a name I've chosen) with Hibernate, so that after it has generated the DDL we can make some updates (which Hibernate doesn't support) to the database?
We need to set a case-insensitive unique constraint on a PostgreSQL column, and while this is perfectly possible in PostgreSQL, it doesn't seem possible within Hibernate/JPA annotations (neither @Table(uniqueConstraint) nor @Column(columnDefinition) nor @Column(unique) quite do what we want).
Thanks in advance
Is there a way to register some kind of SchemaExportEventListener (that's a name I've chosen) with Hibernate
To my knowledge, Hibernate doesn't have anything like that.
so that after it has generated the DDL we can make some updates (which Hibernate doesn't support) to the database?
However, the import.sql feature might help here. With Hibernate, you can put an import.sql file on the root of the classpath and it will get executed after the schema generation (assuming you're using either create or create-drop). Quoting the Rotterdam JBug and Hibernate's import.sql blog post:
Hibernate has a neat little feature that is heavily under-documented and unknown. You can execute an SQL script during the SessionFactory creation right after the database schema generation to import data in a fresh database. You just need to add a file named import.sql in your classpath root and set either create or create-drop as your hibernate.hbm2ddl.auto property.
I use it for Hibernate Search in Action now that I have started the query chapter. It initializes my database with a fresh set of data for my unit tests. JBoss Seam also uses it a lot in the various examples. import.sql is a very simple feature but is quite useful at time. Remember that the SQL might be dependent on your database (ah portability!).
#import.sql file delete from PRODUCTS insert into PRODUCTS (PROD_ID, ASIN, TITLE, PRICE, IMAGE_URL, DESCRIPTION) values ('1', '630522577X', 'My Fair Lady', 19.98, '630522577X.jpg', 'My Fair blah blah...'); insert into PRODUCTS (PROD_ID, ASIN, TITLE, PRICE, IMAGE_URL, DESCRIPTION) values ('2', 'B00003CXCD', 'Roman Holiday ', 12.98, 'B00003CXCD.jpg', 'We could argue that blah blah');
For more information about this feature, check Eyal's blog, he wrote a nice little entry about it. Remember if you want to add additional database objects (indexes, tables and so on), you can also use the auxiliary database objects feature.
This should fulfill your needs.