如何在 orm.xml 中使用 SpEL?

How can I use SpEL inside an orm.xml?

我需要在我的 Spring 应用程序中使用一个 orm.xml 文件,我正在通过执行以下操作创建一个 bean:

@Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
        bean.setPackagesToScan("org.mitre");
        bean.setPersistenceProviderClass(PersistenceProvider.class);
        bean.setDataSource(hikariDataSource);
        bean.setJpaVendorAdapter(jpaAdapter);

        Map<String, String> jpaProperties = new HashMap<>();
        jpaProperties.put("eclipselink.weaving", "false");
        jpaProperties.put("eclipselink.logging.level", "INFO");
        jpaProperties.put("eclipselink.logging.level.sql", "INFO");
        jpaProperties.put("eclipselink.cache.shared.default", "false");

        bean.setJpaPropertyMap(jpaProperties);
        bean.setPersistenceUnitName("defaultPersistenceUnit");

        switch (databaseType){
            case oracle: bean.setMappingResources("db/oracle/entity-mappings_oracle.xml"); break;
            case mssql: bean.setMappingResources("db/mssql/entity-mappings_mssql.xml"); break;
        }

        return bean;
    }

在底部,您可以看到我通过在类路径上提供资源路径来设置映射资源。但是在我的 orm.xml 中,我有以下内容:

<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_0.xsd"
                 version="2.1">

    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <schema>${some.schema.name}</schema>
        </persistence-unit-defaults>
    </persistence-unit-metadata>

</entity-mappings>

我需要 Spring 来扩展 属性,因为架构名称是可配置的。

一种可能是自己获取资源,自己查找并替换属性,然后输出到文件系统。这里的问题是 setMappingResources 采用资源的字符串路径,因此它不能在文件系统上。

另一种可能性是使用 ByteArrayResource 创建内存资源,如下所示:

case mssql: bean.setMappingResources("db/mssql/entity-mappings_mssql.xml");
                String localResource = IOUtils.readFileToString(mssqlMappings.getFile(), Charset.defaultCharset());
                Resource resource = new ByteArrayResource(localResource.replaceAll("${some.schema.name}" ,dbName).getBytes());
                bean.setMappingResources(resource.getFile().getPath());
                break;

但是这不起作用,因为映射资源需要 ByteArrayResource 无法提供的路径。

有什么方法可以在 Java 配置中复制 orm.xml,我可以在其中注入 属性?我乐于接受有关替代方法的建议。

谢谢

如果您想以编程方式更改架构,您可以使用 SessionCustomizer 来完成,并将其添加到您的 jpa 属性中 jpaProperties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, YourSessionCustomizer); 在 YourSessionCustomizer 中,您可以在自定义方法

中更改模式
session.getLogin().setTableQualifier("your_schema")