0

我有一个场景,我必须根据部署应用程序的环境将不同的方言、提供程序加载到我的 persistence.xml 文件中。

例如

在一个环境中我使用 Oracle11g,而在另一个环境中我使用 MySql8。我希望我的 persistnece.xml 看起来像这样。

<persistence-unit name="firstPU" transaction-type="RESOURCE_LOCAL">
        <provider>${somekey.provider}</provider>
        <properties>
            <property name="hibernate.dialect" value="${somekey.dialect}" />
        </properties>
</persistence-unit>

然后有两个单独的属性文件(first.property,second.property)并使用我的 pom.xml 中的构建配置文件选择其中一个。例如-

<profile> 
.
.
.
<build> 
            <resources> 
                <resource> 
                    <directory>src/main/resources/config/${build.profile.id}</directory> 
                    <excludes> 
                    <exclude>**/first.properties</exclude> 
                    </excludes> 
                </resource> 
            </resources> 
        </build>
.
.
.
</profile>

因此,根据选择的配置文件,它将排除一个 .property 文件并从另一个文件中读取。

所有这一切的问题是值从属性文件返回为空。(不再

我在这里遗漏了什么还是有更好的方法来做这种事情?

更新 -

这对于阅读方言值很有效。但是,我无法阅读 Provider !

是否也可以从属性文件中读取 Provider 值?

4

2 回答 2

0

使用占位符放弃并使用 Springpersistence.xml配置。LocalEntityManagerFactory这样,您可以简单地添加属性文件并更改内容,而无需重新创建工件。

创建一个application.properties文件(或您喜欢的任何名称)并添加以下内容

spring.jpa.database-platform=org.hibernate.dialect.OracleDialect

然后,假设您使用基于 java 的配置,添加一个@PropertySource以(可选)从外部位置加载此文件。

@Configuration
@PropertySource("file:/conf/application.properties")
public class MyConfiguration {

    @Autowired
    private Environment env;

    @Bean
    public LocalContainerEntityManagerFactory entityManagerFactory(DataSource ds) {
        LocalContainerEntityManagerFactory emf = new LocalContainerEntityManagerFactory();
        emf.setDataSource(ds);
        emf.setJpaVendorAdapater(jpaVendorAdapter());
        // Other settings
        return emf;
    }

    @Bean
    public HibernateJpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabasePlatform(env.getRequiredProperty("spring.jpa.database-platform"));
        return adapter;
    }
}

现在您可以将方言(和其他属性,如果需要)更改为您喜欢的任何内容。

注意:选择的属性名称与 Spring Boot 中的名称相同,以便在切换到支持所有这些开箱即用的 Spring Boot 时可以重用此配置。

于 2019-04-25T06:09:36.600 回答
-1

您可以在属性文件中定义所有这些数据库详细信息,而不是在 中定义属性persistence.xml,而在构建脚本中,您可以在 war/ear.xml 中包含相应的属性文件。

final Properties persistenceProperties = new Properties();
InputStream is = null;

try {
    is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
    persistenceProperties.load(is);
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

entityManagerFactory = Persistence.createEntityManagerFactory("firstPU", persistenceProperties);

请参阅此链接以获取更多详细信息

于 2019-04-25T05:00:33.643 回答