Hibernate provides a nice way to keep your DB schema in sync with the model. At least 2 choices are available:

– have the hibernate.hbm2ddl.auto set to auto during development

– use various utilities: SchemaExportTask or HibernateToolTask(newer) to generate the full DB schema

For development, first choice worked except for one thing: index creation. All columns were properly created but no index defined. As I found no workaround to that, the only solution was to generate the whole schema.

What if the Hibernate model mixed hbm.xml files with annotations (reused components, mostly)? The SchemaExportTask or HibernateToolTask do not handle the mixed model not to mention the integration with Spring and the missing hibernate.cfg.xml file required by HibernateToolTask.

Only one solution: go to the code and generate the schema by calling the code directly. Easy task actually, I’ve placed the code in a quick Junit test with Spring auto-injection:

/**
 * Maintains DB schema
 *
 * @author icocan
 */
public class SchemaMaintenanceTest extends BaseCommitTestCase {

    private LocalSessionFactoryBean localSessionFactoryBean;

    public void testExportDDL() {
        Configuration configuration = localSessionFactoryBean.getConfiguration();
        SchemaExport export = new SchemaExport(configuration);
        export.setOutputFile("sql.ddl");
        export.setDelimiter(";");
        export.execute(false, false, false, false);
    }

    public void setLocalSessionFactoryBean(LocalSessionFactoryBean localSessionFactoryBean) {
        this.localSessionFactoryBean = localSessionFactoryBean;
    }
}

One response to “Hibernate schema maintenance

Leave a Comment:

Your email address will not be published. Required fields are marked *