繁体   English   中英

如何在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 Config中复制orm.xml并在其中注入属性吗? 我愿意就替代方法提出建议。

谢谢

如果要以编程方式更改架构,则可以使用SessionCustomizer进行更改,并将其添加到jpa属性jpaProperties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, YourSessionCustomizer); 在YourSessionCustomizer中,您可以在custom方法中更改架构

session.getLogin().setTableQualifier("your_schema")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM