本文介绍了在JPA中获取数据库架构名称(来自EntityManager/EntityManagerFactory)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JPA(EclipseLink 2.4)中,我需要在NativeQuery中指定架构名称:
In JPA (EclipseLink 2.4) I need to specify schema name in NativeQuery:
EntityManager em = emf.createEntityManager();
Query query = em.createNativeQuery("select foo from bar.table");
上面的方法可以工作,但是显然我不喜欢对模式名称进行硬编码,特别是考虑到我已经在orm.xml中指定了它的事实:
Above works but obviously I don't like hardcoding schema name, especially given the fact that I'm already specifying it in 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?
推荐答案
如果使用这样的持久性单元:
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>
然后您可以使用EntityManagerFactory提取属性:
You can then use the EntityManagerFactory to extract the properties:
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.
where emf is the already created EntityManagerFactory.
emf = Persistence.createEntityManagerFactory("MY_PU");
这篇关于在JPA中获取数据库架构名称(来自EntityManager/EntityManagerFactory)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!