【问题标题】:JPA: 2 databases: one "update", the other "create"JPA:2个数据库:一个“更新”,另一个“创建”
【发布时间】:2022-01-08 14:49:04
【问题描述】:

我想使用两个数据库架构一个带有静态数据(无法更改),另一个带有动态数据(其中在 Spring 应用程序的执行过程中会不断变化)。

application.properties我已经规定了以下内容:

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/XXXXXX
spring.datasource.username=root
spring.datasource.password=root

spring.second-datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/YYYYYY
spring.second-datasource.username=root
spring.second-datasource.password=root

但是我现在应该如何处理spring.jpa.hibernate.ddl-auto 参数?

对于我要安装的一个方案:

spring.jpa.hibernate.ddl-auto=create

对于其他(数据始终是静态的):

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.ddl-auto=none

【问题讨论】:

    标签: java mysql spring hibernate jpa


    【解决方案1】:

    您有一个需要两个不同数据源的问题。您应该将它们定义为 2 个不同的 bean 并分别自动装配它们。为清楚起见,建议同时使用 2 个不同的属性文件。

    您可以创建一个配置类并使用特定的属性文件来填充字段,如下所示:

    @Configuration
    @PropertySource("classpath:db.properties")
    public class Config {
    
      @Value("${db.driverClassName}")
    String driverClassName;
    
      @Value("${db.url}")
    String url;
    
      @Value("${db.username}")
    String username;
    
      @Value("${db.password}")
    String password;
    
    
      @Bean("datasourceId")
      public DataSource dataSource() {
        var dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
      }
    
    
    
      @Bean
      public LocalSessionFactoryBean sessionFactory() {
            LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(
          { "com.foo.bar" });
        sessionFactory.setHibernateProperties(hibernateProperties());
    
        return sessionFactory;
      }
    
      private final Properties hibernateProperties() {
            Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty(
          "hibernate.hbm2ddl.auto", "create-drop");    
        return hibernateProperties;
      }
    }
    

    【讨论】:

    • 感谢您的回复。即使我用这种方式将两个数据库模式分开,我如何指示一个数据源需要重新创建,而另一个不需要?
    • 更新了我的答案,以展示如何为休眠定义会话工厂,该工厂使用所述数据源和属性,您可以在其中定义所需的填充方法。
    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多