简体   繁体   中英

JPA and PostgreSQL

I'm on a project that uses the EclipseLink implementation of JPA to talk to a PostgreSQL database. I have a task for which PostgreSQL NOTIFY/LISTEN seems like a perfect fit. Unfortunately, I'm a JPA newb, and am struggling to figure out how to make it work. So I guess I really have two questions; answering either one will make me happy.

1) What's the best way for me to get a hold of the direct JDBC connection to the database? (Which I sincerely hope will prove to be of type org.postgresql.PGConnection .)

OR

2) What's the best way for me to emulate/access org.postgresql.PGConnection.getNotifications() via EclipseLink JPA?

Thank you very much for your help.


Two working solutions! 两个工作解决方案! I love this site. If anybody has anything to say about hidden gotchas/benefits that would make either Pascal's or Balus's solution better than the other before I hand out the checkmark, I'd like to hear it.

Getting a JDBC connection from an EntityManager in EclipseLink is answered in the EclipseLink wiki .

The way differs per JPA API version. Here's an extract from the wiki:

JPA 2.0

entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

JPA 1.0

entityManager.getTransaction().begin();
UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl)((JpaEntityManager)entityManager.getDelegate()).getActiveSession();
unitOfWork.beginEarlyTransaction();
java.sql.Connection connection = unitOfWork.getAccessor().getConnection();
...
entityManager.getTransaction().commit();

您应该能够从EntityManager.getDelegate()返回的org.eclipse.persistence.internal.jpa.EntityManagerImpl中获取它:

java.sql.Connection conn = ((EntityManagerImpl)(em.getDelegate())).getServerSession().getAccessor().getConnection();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM