Hibernate schema maintenance

2 min read >

Hibernate schema maintenance

Engineering Insights & Enterprise solutions

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 an auto during development

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

For development, the first choice worked except for one thing: index creation. All columns were properly created but no index was 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. The 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;
    }
}

Unlock innovation and digital transformation for your business.

Get in touch

We are always happy to talk

Phone

+40-21-223-7700

Email

hello@tremend.com

Address

165 Splaiul Unirii, Timpuri Noi Square,
TN Office 2 building, 4th floor,
District 3, Bucharest, Romania, 030134