2013-03-12 68 views
3

在JPA(2.4的EclipseLink)我需要NativeQuery指定架構名稱:獲取JPA數據庫架構名稱(從EntityManager的/ EntityManagerFactory的)

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> 

當然,必須有辦法從某處獲取運行時的架構名稱?

回答

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"); 
+1

P.S.這對於至少SQL Server不起作用,因爲它的jdbc url如下所示:jdbc:sqlserver:// localhost:1433; databaseName = dbname – 2017-04-12 16:56:09

相關問題