我需要在 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,以便在其中注入(inject)属性?我愿意接受有关替代方法的建议。
谢谢
最佳答案
如果您想以编程方式更改架构,您可以使用 SessionCustomizer 来完成此操作,并将其添加到您的 jpa 属性 jpaProperties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, YourSessionCustomizer);
在 YourSessionCustomizer 中,您可以在自定义方法中更改架构
session.getLogin().setTableQualifier("your_schema")
关于java - 如何在 orm.xml 中使用 SpEL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630562/