如何在JavaEE6中从JPA2 EntityManager获取数据源或连接
我有一个正在运行的应用程序,其中我使用JavaEE6和EclipseLink实现持久化,并使用PostgreSQL数据库 对于用户注册,我想将PostgreSQL中的密码设置为:如何在JavaEE6中从JPA2 EntityManager获取数据源或连接,java,jpa,jdbc,java-ee-6,Java,Jpa,Jdbc,Java Ee 6,我有一个正在运行的应用程序,其中我使用JavaEE6和EclipseLink实现持久化,并使用PostgreSQL数据库 对于用户注册,我想将PostgreSQL中的密码设置为: ... password = crypt('inputPassword',gen_salt('bf')) ... 因为我不能使用DigestUtils,所以我必须手动将用户插入数据库。 为了保持应用程序的可配置性,我不想使用 InitialContextInstance.lookup(dataSource)但要以某种
... password = crypt('inputPassword',gen_salt('bf')) ...
因为我不能使用DigestUtils,所以我必须手动将用户插入数据库。
为了保持应用程序的可配置性,我不想使用
InitialContextInstance.lookup(dataSource)
但要以某种方式从EntityManager中提取它(或连接)
比如:
或者可以同时使用createNativeQuery或类似的东西吗
有一个预先准备好的声明来防止注射?有时只需要在谷歌上运行一次:
entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();
正如在回答“阿基米德·特拉亚诺”对公认答案的评论时所述,公认答案是否适用于Eclipselink以外的情况?答案是否定的,至少是冬眠
当我尝试hibernate的公认答案时,出现以下错误:
Caused by: org.springframework.orm.jpa.JpaSystemException: Hibernate cannot unwrap interface java.sql.Connection; nested exception is javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418) ~[spring-orm-4.0.5.RELEASE.jar:4.0.5.RELEASE]
下面的stackoverflow问题的答案让我想到了一个适用于Hibernate的解决方案
以下是我的解决方案:
Session hibernateSession = entityManager.unwrap(Session.class);
hibernateSession.doWork(new org.hibernate.jdbc.Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do whatever you need to do with the connection
}
});
根据dulon的回答,下面是一段与Hibernate4一起工作的代码
Connection getConnection() {
Session session = entityManager.unwrap(Session.class);
MyWork myWork = new MyWork();
session.doWork(myWork);
return myWork.getConnection();
}
private static class MyWork implements Work {
Connection conn;
@Override
public void execute(Connection arg0) throws SQLException {
this.conn = arg0;
}
Connection getConnection() {
return conn;
}
}
如果您将数据源用于JPA配置,则应该能够使用
@Resource(name=“myDb”)数据源myDb来访问它。不是吗?我想你也可以用JPA定义参数化查询。是的,这可能行得通,但我仍然需要知道名称。我想为注入的EntityManager获取配置的默认数据源。这是标准的一部分。这似乎是特定于Eclipselinkis的,有没有一种方法可以从这个连接中获取密码在JPA+JTA(JavaSDK8U31)+WebSphere8.5.5上工作的好答案
Connection getConnection() {
Session session = entityManager.unwrap(Session.class);
MyWork myWork = new MyWork();
session.doWork(myWork);
return myWork.getConnection();
}
private static class MyWork implements Work {
Connection conn;
@Override
public void execute(Connection arg0) throws SQLException {
this.conn = arg0;
}
Connection getConnection() {
return conn;
}
}