2

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
1
  • Note that the setting spring.jpa.hibernate.ddl-auto=update won't drop a column if you remove the column from your @Entity class. It will drop and recreate it only if you change the column type. Commented May 6, 2018 at 13:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

IMPORTANT: These lines will completely delete all data in your database: properties.put("hbm2ddl.auto", "create"); properties.put("hibernate.hbm2ddl.auto", "create");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.