在JPA(EclipseLink 2.4)中,我需要在NativeQuery中指定模式名称:
EntityManager em = emf.createEntityManager();
Query query = em.createNativeQuery("select foo from bar.table");
以上工作,但显然我不喜欢硬编码模式名称,特别是考虑到我已经在orm.xml中指定了它:
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>bar</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
当然必须有一种方法可以从某个地方获取运行时的模式名称吗?
答案 0 :(得分:2)
这里提出了一个非常相似的问题,可能不是理想的答案:Access JPA <persistence-unit-metadata> programmatically
答案 1 :(得分:1)
如果使用这样的持久性单元:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="">
<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
...................................
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://something:5432/MY_DB_NAME"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<property name="eclipselink.logging.level" value="WARNING"/>
</properties>
然后,您可以使用EntityManagerFactory提取属性:
public String getDatabaseName() {
String dbName = null;
Map<String, Object> map = emf.getProperties();
String url = (String) map.get("javax.persistence.jdbc.url");
if(url != null) {
dbName = url.substring(url.lastIndexOf("/") + 1);
}
return dbName;
}
其中 emf 是已创建的EntityManagerFactory。
emf = Persistence.createEntityManagerFactory("MY_PU");