以编程方式在springboot中设置hibernate.ddl-auto [英] Set hibernate.ddl-auto in springboot programmatically

查看:449
本文介绍了以编程方式在springboot中设置hibernate.ddl-auto的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在非Web应用程序和数据JPA中使用springboot.我使用默认配置,但数据源除外:

I use springboot in a non web application and data jpa. I use the default configuration except for datasource:

private static final String dataSourceUrl = "jdbc:h2:./Database;DB_CLOSE_ON_EXIT=FALSE";
@Bean
public DataSource dataSource() {
    return DataSourceBuilder.create().url(dataSourceUrl).username("user").password("pwd").build();
}

如何通过编程方式设置spring.jpa.hibernate.ddl-auto属性?

How can I set the spring.jpa.hibernate.ddl-auto property also programmatically?

推荐答案

添加以下bean似乎可以完成这项工作(由于Jens的评论):

Adding the following bean seems to do the job (thanks to Jens' comment):

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan(new String[] { "packages.to.scan" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);

    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    em.setJpaProperties(properties);

    return em;
  }

这篇关于以编程方式在springboot中设置hibernate.ddl-auto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆