3

在 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>

当然必须有一种方法可以在运行时从某个地方获取模式名称?

4

1 回答 1

2

如果使用这样的持久性单元:

<?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");
于 2016-04-20T09:35:19.673 回答