Search code examples
jakarta-eejava-ee-6

Java EE 6 JDBC Connection stickyness


I have a simple DAO that accesses JDBC connections via a DataSource.

When I call both operation1() and operation2() within a parent business EJB it actually uses two connections from the pool which seems to cause a performance issue at high volumes of calls since the pool is only so big.

1) The Connection I use must be container managed. So unwrapping the EntityManager's connection is not an option.

2) Under the hood EclipseLink is being used.

How do I get a single connection without polluting my parent business EJB with JDBC handling ?

@Stateless
public class MyDAO {
    @Resource(name = "jdbc/bla")
    private DataSource ds;

    public void operation1() {
        try (
            Connection connection = ds.getConnection();
            CallableStatement cs = connection.prepareCall(xxx);) {

        }
        ...
    }
    public void operation2() {
        try (
            Connection connection = ds.getConnection();
            CallableStatement cs = connection.prepareCall(yyy);) {

        }
        ...
    }

Solution

  • Change:

    @Resource(name = "jdbc/bla")
    private DataSource ds;
    

    to:

    @PersistenceContext(unitName = "myPU")
    private EntityManager em;
    

    Then define a JTA datasource in your persistence.xml which maps to "myPU". That JTA datasource should map to JDBC resource that points to a JDBC connection pool. Both the JDBC resource and JDBC connection pool will be configured in your EE6 application server.

    With that setup you will have connection pooling to your datasource and when you call operation1() and operation2() from a parent EJBs method they will be part of the same connection/transaction.