el_pup_le
el_pup_le

Reputation: 12179

Updating database schema with hibernate spring boot

Is it possible to update a database schema whenever the program is run? I've used ddl auto update but it doesn't add or remove columns some of the time so I have to edit to ddl-auto=create then back to =update do the schema update. Why does it not update the schema consistently, I'd rather not use a migration tool until closer to production. So ideally when I add a field to an entity or remove it, it should just try update the scheme next time the program is run.

spring.jpa.hibernate.ddl-auto=update

Upvotes: 2

Views: 7910

Answers (1)

Martin
Martin

Reputation: 2235

The way I do it is i read a value from an external config file when i create my session factory, hope this helps :

private Properties hibernateProperties() 
{
    Properties properties = new Properties();
    properties.put("hibernate.connection.driver_class","net.sourceforge.jtds.jdbc.Driver");
    properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");

    if (environment.getProperty("dbReset").compareTo("ON") == 0)
    {
        properties.put("hbm2ddl.auto", "create");
        properties.put("hibernate.hbm2ddl.auto", "create");
    }

    properties.put("javax.persistence.validation.mode", "none");
    properties.put("hibernate.jdbc.batch_size", "50");
    properties.put("hibernate.cache.use_second_level_cache", "false");
    properties.put("hibernate.c3p0.min_size", "50");
    properties.put("hibernate.c3p0.max_size", "100");
    properties.put("hibernate.c3p0.timeout", "300");
    properties.put("hibernate.c3p0.max_statements", "50");
    properties.put("hibernate.c3p0.idle_test_period", "3000");

    return properties;        
}

This allows me to completely reset the DB if i've made structure changes to the underlying DB when adding new features for example. I also have a method to create test data that works in a similar way.

You'll notice i have 2 properties in there. It's been a while but i seem to recall similar issues when i only had one. I do know for a fact that if i add a column to an entity and my dbReset mode is on everything is taken care of for me by Hibernate, every time.

Upvotes: 1

Related Questions