The problem is that Hibernate's SchemaExport class requires a org.hibernate.cfg.Configuration class to be passed in. Configuring this within Spring based applications is sparsely documented (Furthermore, the Configuration class is not easy to get hold off) but nevertheless there are some good pointers on how to get the Configuration object, when using straight Hibernate e.g:
Unfortunately, I am a bit on the cutting edge and I configured my persistence using
- org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean and
- org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
That discussion pointed to the following blog post:
That was pretty much it. The blog post gave me some ideas about where to look next for answers (the Hibernate and Spring source code ;-), but the example just felt a bit heavy for my use-case. Everything was already configurred using Spring/JPA in my environment. Why shouldn't I be able to reuse my existing infrastructure to use the SchemaExport class?
The solution
After some more searching, I think I found a workable example:
In my class I inject the LocalContainerEntityManagerFactoryBean:
@Autowired LocalContainerEntityManagerFactoryBean fb;
Then I use the following code to setup SchemaExport:
org.hibernate.ejb.Ejb3Configuration cfg = new org.hibernate.ejb.Ejb3Configuration();
org.hibernate.ejb.Ejb3Configuration configured =
cfg.configure(fb.getPersistenceUnitInfo(), fb.getJpaPropertyMap()); org.hibernate.tool.hbm2ddl.SchemaExport schemaExport =
new org.hibernate.tool.hbm2ddl.SchemaExport(configured.getHibernateConfiguration());
And then do whatever you need to, such as printing the SQL Schema DDL to the console: schemaExport.create(true, false);
Not that bad after all. If you have similar needs, hopefully the Google gods are with you and this blog posting showed up in your search results. See you next time.