【发布时间】:2018-04-03 12:50:53
【问题描述】:
我需要在我的 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,我可以在其中注入属性?我愿意接受有关替代方法的建议。
谢谢
【问题讨论】:
-
您不能在
orm.xml中使用 SpEL,仅 JPA 不涉及 Spring,而 JPA 不允许您这样做。 Hibernate 有一个属性,您可以使用它来设置默认模式。 EclipseLink 可能有类似的东西
标签: java spring jpa eclipselink