如何使用spring创建2个数据库连接

时间:2017-05-01 07:44:13

标签: java jpa spring-boot database-connection datasource

如何使用spring创建2个数据库连接?

例如,连接需要具有单独的datasourcejpa(适用于show-sqlproperties.hibernate.dialect)属性。

# Foo
foo.datasource.url=...
foo.jpa.properties.hibernate.dialect=... # H2
# Bar
bar.datasource.url=...
bar.jpa.properties.hibernate.dialect=... # ORACLE

我想要实现的不是配置本身,而是使用application.properties配置属性的方式

所有我能找到的是创建2个数据源。所以我提出了一个执行此操作的代码,但它看起来很脏,并且仅支持jpa.show-sql jpa.properties.hibernate.show_sql

在代码中,我使用@ConfigurationProperties展开Mapfoo: { jpa: { properties: { database: "H2" } } } } -> { "foo.jpa.properties.database": "H2" })并调用EntityManagerFactoryBuilder.Builder#properties(Map)

来阅读spring中的属性

有人有更好的解决方案吗?

我的代码:

// I Copied the code by hand because we code on isolated network
private static final String NAME = "foo"

@Bean
@ConfigurationProperties(NAME + "datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource, Map<String,String> properties, EntityManagerFactoryBuilder builder) {
    return builder.dataSource(dataSource)
        .packages(NAME + ".entitites")
        .properties(properties)
        .persistenceUnit(NAME)
        .build()
}


@Bean
@ConfigurationProperties(NAME + "jpa.properties")
public Map<String, ?> propertiesNotFlatten() {
    retur new HashMap<String, ?>();
}

@Bean
public Map<String, String> properties(Map<String, ?> propertiesNotFlatten) {
    return flatten(propertiesNotFlatten)
        .collect(toMap(Entry::getKey, Entry::getValue));
}

private static Stream<Entry<String, String> flatten(Map<String, ?> map) {
    return map.entrySet()
        .stream()
        .flatMap(x -> x.getValue() instanceof String
            ? Stream.of((Entry<String, String>)x)
            : flatten(((Map<String, ?>)x.getValue())).map(y -> new SimpleEntry<>(
                x.getKey() + "." + y.getKey(),
                y.getValue()
            ))
        );
}

请注意我的代码有效,我只想知道如何做得更好(春天必须有更好的方法来做到这一点)

0 个答案:

没有答案