## Monday, May 29, 2006

### Exporting database schemas with Spring/Hibernate

If you are using Hibernate, you can use schemaexport create your database schema from your mapping files by including the following in your Ant build file:

<!--
You will want to modify your runtime classpath to
include the hibernate jar.
//-->
classpathref="runtime.classpath">

<!--
This assumes your hibernate.cfg.xml is in the default
package; the resulting SQL will be saved in the tmp
directory.
//-->
<schemaexport
casesensitive="true"
config="${build.dir}/hibernate.cfg.xml" output="${tmp.dir}/schema-export.sql"
haltonerror="true"/>

However, this assumes the existence of a hibernate.cfg.xml file. If you are using Spring with Hibernate, you will typically configure Hibernate via Spring's configuration file. So where do you tell schemaexport your configuration is?

As far as I know, you can't. Instead, you have to do this programmatically by using LocalSessionFactoryBean#createDatabaseSchema . See the following code, and notice the "&" in front of the bean name; if you don't include the "&", you will get a SessionFactory rather than the bean:

// This assumes your LocalSessionFactoryBean is named "sessionFactory"
LocalSessionFactoryBean bean
= (LocalSessionFactoryBean) ctx.getBean("&sessionFactory");
bean.createDatabaseSchema();

From here on, you may write your own task or simply use the java task to run a little utility to create your database schema whenever you need to.