commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <craig...@apache.org>
Subject Re: DBCP : some questions.
Date Wed, 29 Oct 2003 04:33:59 GMT
Antony Paul wrote:

>Thank you for the reply.
>
>For transaction support previously I was turning the AutoCommit off and then
>the connection is put in the session and forwarded to next JSP/servlet and
>closed the connection after use. Is it the right method. Or there is any
>better method.
>
>In DBCP example using JNDI this code  is used to get connection.
>Context initContext = new InitialContext();
>Context envContext  = (Context)initContext.lookup("java:/comp/env");
>DataSource ds = (DataSource)envContext.lookup("jdbc/Test");
>Connection conn = ds.getConnection();
>
>putting this code in every page,servlet and bean is not a good idea(lot of
>typing and importing all class files). Any better method for doing it.
>
>  
>
Well, cut-and-paste in any competent editor can avoid the typing :-).  
But your point is well taken -- it's good to centralize utility things 
like this.  If your various processing classes that need a connection 
happen to inherit from a base class (such as if you're using Struts, and 
all your Actions need to be able to look up data sources), you can 
create a method like this in a base class, which then becomes available 
to all the subclasses (modulo some exception handling):

    protected Connection getConnection(String name) {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource) envContext.lookup("jdbc/Test");
        return (ds.getConnection());
    }

and getting a connection collapses to a single line:

    Connection conn = getConnection("jdbc/Test");

If you're not sharing subclasses, it's also just as easy to make the 
getConnection() method "public static" in a utility class (say, called 
"Util"), instead of "protected" in your base class; then the one-liner 
changes to:

    Connection conn = Util.getConnection("jdbc/Test");

If you now and forevermore know that the one-and-only connection you 
will ever request is "jdbc/Test", you could even omit the argument, but 
I would suggest that is not a good practice because it reduces the 
reusability of this method in different environments.

Note that this same general approach is useful for *any* resource that 
your app server makes available via JNDI, not just connection pools.

>Antony Paul
>
>  
>

Craig McClanahan



---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Mime
View raw message