java 在 JPA 中获取 DB 模式名称(来自 EntityManager/EntityManagerFactory)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15351308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get DB schema name in JPA (from EntityManager/EntityManagerFactory)
提问by maximdim
In JPA (EclipseLink 2.4) I need to specify schema name in NativeQuery:
在 JPA (EclipseLink 2.4) 中,我需要在 NativeQuery 中指定模式名称:
EntityManager em = emf.createEntityManager();
Query query = em.createNativeQuery("select foo from bar.table");
Above works but obviously I don't like hardcoding schema name, especially given the fact that I'm already specifying it in orm.xml:
以上工作,但显然我不喜欢硬编码模式名称,特别是考虑到我已经在 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>
Surely there must be a way to get schema name on runtime from somewhere?
当然必须有一种方法可以从某个地方在运行时获取模式名称?
回答by kirilv
If using a persistence unit like this:
如果使用这样的持久化单元:
<?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>
You can then use the EntityManagerFactory to extract the 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;
}
where emfis the already created EntityManagerFactory.
其中emf是已经创建的 EntityManagerFactory。
emf = Persistence.createEntityManagerFactory("MY_PU");