2
\$\begingroup\$

I have the following DAOParent class that I use to put connect/disconnect code in one place. Each DAO class in the application is an EJB that extends DAOParent (note that I don't use JPA):

public class DAOParent {

    private InitialContext context = null;
    private DataSource ds = null;
    private Connection conn = null;

    protected Connection getConnFromPool(String pool) throws DAOException { 

        try {
            context = new InitialContext();
            ds = (DataSource)context.lookup(pool);
            conn = ds.getConnection();
            return conn;
        } 
        catch (NamingException e) {
            throw new DAOException(e.getMessage());
        } 
        catch (SQLException e) {
            throw new DAOException(e.getMessage());
        }
    }


    protected void releaseConn() {
        try {
            if (conn != null)
                conn.close();
        } 
        catch (SQLException e) {}

        try {
            if (context != null)
                context.close();
        } 
        catch (NamingException e) {}
    }
}

And the DAO class:

@Stateless
public class DAOChild extends DAOParent {

    public void someMethod() throws DAOException {

        Connection conn = getConnFromPool("some/jndi/path");

        try {

            // use the connection
        } 
        finally {
            releaseConn();
        }
    }
}

The DAOChild class is then injected in an EJB to access the data.

Questions: (1) is there a problem with this approach? (2) If I have DAOChild1 and DAOChild2 injected in the same EJB, is there a conflict in the connection lookup?

I run this on Wildfly 14 application server/container.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.