Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Eclipse Projects » EclipseLink » How to obtain connection from EntityManagerFactory?
How to obtain connection from EntityManagerFactory? [message #517893] Tue, 02 March 2010 08:19 Go to next message
Olu  is currently offline Olu
Messages: 29
Registered: October 2009
Junior Member
How do I obtain a connection handler for the underlying connection made by the EntityManagerFactory?

I'm writing an desktop app and need to access the dB. My persistence unit uses an embedded url connection.

Currently I do this by starting JavadB in server mode and get another separate connection on port 1527 as follows:-

// Start JavadB in server mode
 try {
            server = new NetworkServerControl();
            server.start(new PrintWriter(System.out, true));

        } catch (Exception ex) {
            Logger.getLogger(CBTv01View.class.getName()).log(Level.SEVERE, null, ex);
        }

//Get connection to above server

        ClientDataSource ds = new ClientDataSource();
        ds.setPortNumber(1527);
        ds.setDatabaseName(dbName1);
        try {
            conn = ds.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(CBTv01View.class.getName()).log(Level.SEVERE, null, ex);
        }


The above approach can be useful in development as you can connect to the dB from debug apps etc. However, it seems expensive on resources for deployment and I would like to reuse the connection the EntityManagerFactory has made.

Thanks,
Re: How to obtain connection from EntityManagerFactory? [message #518046 is a reply to message #517893] Tue, 02 March 2010 15:47 Go to previous messageGo to next message
James Sutherland is currently offline James Sutherland
Messages: 1834
Registered: July 2009
Senior Member
You can get the EclipseLink ServerSession from the factory and get the read or write ConnectionPool from the ServerSession, and then get the currently available connections (DatabaseAccessor) from the pool, and then get the JDBC connections from them.

You can also get the JDBC connection from an EntityManager, if using EclipseLink / JPA 2.0 just call em.unwrap(java.sql.Connection.class).



James : Wiki : Book : Blog
Re: How to obtain connection from EntityManagerFactory? [message #518112 is a reply to message #517893] Wed, 03 March 2010 01:50 Go to previous message
Olu  is currently offline Olu
Messages: 29
Registered: October 2009
Junior Member
Thanks.

This works:-

conn = ((EntityManagerImpl) (entityManager.getDelegate())).getServerSession().getAccessor().getConnection();


Previous Topic:Caching Behavior for @ReadOnly Entities?
Next Topic:Problem with Cascade.REMOVE with OneToMany relationship JSE [FIXED]
Goto Forum:
  


Current Time: Tue May 21 20:35:51 EDT 2013

Powered by FUDForum. Page generated in 0.01600 seconds