使用hibernate spring boot更新数据库模式

时间:2018-05-06 13:01:31

标签: java hibernate spring-boot

是否可以在程序运行时更新数据库模式?我已经使用了ddl自动更新,但它不会在某些时候添加或删除列,所以我必须编辑到ddl-auto=create然后再回到=update进行架构更新。为什么它不能一致地更新架构,我宁愿不使用迁移工具,直到更接近生产。因此,理想情况下,当我向实体添加字段或删除它时,它应该在下次运行程序时尝试更新方案。

spring.jpa.hibernate.ddl-auto=update

1 个答案:

答案 0 :(得分:1)

我这样做是因为我在创建会话工厂时从外部配置文件中读取了一个值,希望这会有所帮助:

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;        
}

如果我在添加新功能时对基础数据库进行了结构更改,则允许我完全重置数据库。我还有一种方法来创建以类似方式工作的测试数据。

你会注意到我有2个属性。已经有一段时间但我似乎还记得类似的问题,当时我只有一个。我知道一个事实,如果我向一个实体添加一个列并且我的dbReset模式已经开启,Hibernate每次都会为我处理所有事情。