Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EclipseLink JPA 2.1 User supplied connection

I would like to use EclipseLink as my JPA engine. We are using a subclass of java.sql.Connection and I would like to know if I can force EclipseLink to use my connection. I would like to set the connection object programmatically.

Something like

MyConnection conn = new MyConnection(JDBC_URL, USR, PWD);
EntityManagerFactory factory = Persistence.createEntityManagerFactory(conn);
like image 494
Andrea Avatar asked Feb 01 '26 17:02

Andrea


1 Answers

You can set a custom connection programatically using the following code:

Map properties = new HashMap();

// Configure the internal EclipseLink connection pool
properties.put(JDBC_DRIVER, "oracle.jdbc.OracleDriver");
properties.put(JDBC_URL, "jdbc:oracle:thin:@localhost:1521:ORCL");
properties.put(JDBC_USER, "user-name");
properties.put(JDBC_PASSWORD, "password");
Persistence.createEntityManagerFactory("unit-name", properties);

I found this answer here after a quick google search:

http://eclipse.1072660.n5.nabble.com/Defining-persistence-xml-programatically-td2536.html

I dont believe that there is a way to force Eclipselink to connect using only that java.sql.Connection; not out of the box at least. You could make a simple utility method to pass in said connection and build a properties map as I described above.

public Map convertConnectionToProperties(Connection conn) {
    // Do the mapping

    return theMap;
}

If you take a look at this link you will see that

Persistence.java

createEntityManagerFactory(String persistenceUnitName) 
createEntityManagerFactory(String persistenceUnitName, Map properties) 

That is all it can take as parameters. Simply put; what you are asking for simply isn't possible without taking your connection object and adjust it to return something that complies with what createEntityManagerFactory can take in.

class MyConnection {
     // Your code here
    
    public Map convertToMap() {
        // Do the mapping

        return theMap;
    }

    public String getPersistenceUnitName() {
        return "Some-Name";
    }
}

And then utilize it like this:

MyConnection conn = new MyConnection(JDBC_URL, USR, PWD);
EntityManagerFactory factory = Persistence.createEntityManagerFactory(conn.getPersistenceUnitName(), conn.convertToMap());
like image 120
Mister Avatar answered Feb 03 '26 08:02

Mister