Best practice for initializing JDBC connection in Servlets.

A

Alex Polite

I'm starting out with servlets.

I'm wondering about best practices for initializing JDBC
connections. I've tried doing it in the servlet constructor and in
doGet. Intuitively the constructor feels like the right place, but I
wonder if there could be negative consequences when multiple clients
access the servlet simultaneously? Or maybe I should do it in the init
method?

Any recommended reading available online?
alex
 
K

Kevin McMurtrie

Alex Polite said:
I'm starting out with servlets.

I'm wondering about best practices for initializing JDBC
connections. I've tried doing it in the servlet constructor and in
doGet. Intuitively the constructor feels like the right place, but I
wonder if there could be negative consequences when multiple clients
access the servlet simultaneously? Or maybe I should do it in the init
method?

Any recommended reading available online?
alex

For a very simple and low traffic service, it may be acceptable to
initialize the JDBC driver in init() and manage connections in doGet().

For best performance you should manage the JDBC connections outside the
servlet. A JDBC pool can cache connections during frequent use to
eliminate the overhead of establishing and destroying connections.
Often there's one pre-loading Servlet that does nothing except
initialize the application context, like the JDBC pooling.

Eventually you'll want to move all JDBC code out of the servlets. The
software will be easier to scale if the servlets only have to deal the
interface between an HTTP client and the server's data, not management
of the data too.
 
R

Roedy Green

I'm wondering about best practices for initializing JDBC
connections. I've tried doing it in the servlet constructor and in
doGet. Intuitively the constructor feels like the right place, but I
wonder if there could be negative consequences when multiple clients
access the servlet simultaneously? Or maybe I should do it in the init
method?

I put in the init method, but I'm no so sure that is wise. I have
discovered sometimes MySQL just drops the connection. Perhaps is has
an inactivity timeout. I am going to have to rig up something to try
to recover gracefully from that.
 
S

Sudsy

Roedy said:
I put in the init method, but I'm no so sure that is wise. I have
discovered sometimes MySQL just drops the connection. Perhaps is has
an inactivity timeout. I am going to have to rig up something to try
to recover gracefully from that.

I specify a connection pool data source in the container. It handles
all the nastiness automagically. Otherwise you'd have to make your own
code much more complex, handling disconnections and attempting to re-
connect, handling retry counts, etc. Obviously it CAN be done, but why
bother?
 
J

Job Numbers

Alex Polite said:
I'm starting out with servlets.

I'm wondering about best practices for initializing JDBC
connections. I've tried doing it in the servlet constructor and in
doGet. Intuitively the constructor feels like the right place, but I
wonder if there could be negative consequences when multiple clients
access the servlet simultaneously? Or maybe I should do it in the init
method?

Any recommended reading available online?
alex

Just use Spring, and when you make a datasource, just use
org.apache.commons.dbcp.BasicDataSource in jakarta's "commons-dbcp.jar".
This gives a datasource that is global to the application, is not in your
servlets (or spring controllers or whatever) and it's good performance-wise.
 
J

Job Numbers

Sudsy said:
I specify a connection pool data source in the container. It handles
all the nastiness automagically. Otherwise you'd have to make your own
code much more complex, handling disconnections and attempting to re-
connect, handling retry counts, etc. Obviously it CAN be done, but why
bother?

Or you can just use spring...
 
A

Alex Polite

Thanks everyone who replied.

You convinced me that connection pooling is the way to go. But a few
minutes of Googling revealed that there are a lot of ways to do this
in Java.

I want a library that is dead simple to use and well maintained. No
one-man shows.

What contenders am I looking at?

alex
 
J

Job Numbers

Alex Polite said:
Thanks everyone who replied.

You convinced me that connection pooling is the way to go. But a few
minutes of Googling revealed that there are a lot of ways to do this
in Java.

I want a library that is dead simple to use and well maintained. No
one-man shows.

What contenders am I looking at?

alex

I already said. Jakarta's database pooling library is used with spring
because

1) you don't even need to know it's there
2) if it's not good enough in the future, you can change it for something
else without any changes in your other code
3) you should just be using spring anyway. www.springframework.org
 
A

Alex Polite

I already said. Jakarta's database pooling library is used with spring
because

1) you don't even need to know it's there
2) if it's not good enough in the future, you can change it for something
else without any changes in your other code
3) you should just be using spring anyway. www.springframework.org


I don't know. The word "framework" sort of puts me off. I've come to
associate it with unclear objectives and lots of browsing through
thick manuals. Last time I tried to get into a web development
framework was Zope. Two years later I still don't know what Zope is
good for.

After poking around www.springframework.org for 15 minutes I have no
clue as to what Spring is supposed to do. That to me is a bad sign.

Maybe you could turn me around? For example by showing me some Spring
code that does DB connection pooling side to side with code using some
alternative library and demonstrate that Spring is simpler.

alex
 
J

Job Numbers

I don't know. The word "framework" sort of puts me off. I've come to
associate it with unclear objectives and lots of browsing through
thick manuals. Last time I tried to get into a web development
framework was Zope. Two years later I still don't know what Zope is
good for.

After poking around www.springframework.org for 15 minutes I have no
clue as to what Spring is supposed to do. That to me is a bad sign.

Maybe you could turn me around? For example by showing me some Spring
code that does DB connection pooling side to side with code using some
alternative library and demonstrate that Spring is simpler.

alex

Spring is a framework that makes writing J2EE applications a lot easier.
It's not a "lock-me-in" framework since it's very simple and very light, and
all of it works on interfaces. This means you can just implement a new
interface, swap out the old component for your new one. Just read the
reference documentation. You don't have to read the whole thing, just get
your feet wet with the bean factories. I don't know how anyone could
develop without dependancy injection nowadays.

<!-- DATASOURCE -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property
name="driverClassName"><value>org.postgresql.Driver</value></property>
<property
name="url"><value>jdbc:postgresql://localhost:5432/databasename</value></property>
<property name="username"><value>username</value></property>
<property name="password"><value>password</value></property>
</bean>


This is an example of configuring a datasource (note it's
org.apache.commons.dbcp.BasicDataSource in this case, but it can be any
datasource that follows the interface). You can then pass this datasource
into other beans, like a hibernate session factory, and they won't even need
to know that you've changed databases.

Just read the reference docs. I can't explain it all to you when they
already did a fine job already. Just use it, because it's not one of those
frameworks that will disappear tomorrow. In fact, it's gaining popularity
everyday and it's considered very standard in terms of open source
enterprise projects (web or not web).
 
R

Roedy Green

<!-- DATASOURCE -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property
name="driverClassName"><value>org.postgresql.Driver</value></property>
<property
name="url"><value>jdbc:postgresql://localhost:5432/databasename</value></property>
<property name="username"><value>username</value></property>
<property name="password"><value>password</value></property>
</bean>

To me the equivalent java is much terser and more readable. I don't
see what you are gaining.
 
J

Job Numbers

Roedy Green said:
To me the equivalent java is much terser and more readable. I don't
see what you are gaining.

Nobody needs to know what the datasource is, just that implements
datasource. You don't have configuration in source files. You can just
edit the configuration and restart the app without a recompile. The object
is just a bean, so it's not tied to any other framework. The bean itself
just does it's own job. Spring just ties them together. Beans don't know
about spring, which means if you wanted to remove spring entirely, you
wouldn't have to do all that much if anything to your actual program other
than wire it all up manually (which is a pain in the ass).

Just read the docs before making all of these assumptions. Odds are, if you
have never used a light-weight container using dependany injection, you
aren't writing large scale apps properly. Of course, spring isn't your only
option. You can use other open source alternatives that do something
similar, but Spring is by far the best one available. I don't know what to
say. Just read it and spend a day or two learning it. It really isn't that
hard and you'll definately see the advantages compared to your old code. Of
course, if you have no multi-tiered apps to compare it with, I can see why
you wouldn't get it.
 
S

Sudsy

Job Numbers wrote:
Just read the docs before making all of these assumptions. Odds are, if you
have never used a light-weight container using dependany injection, you
aren't writing large scale apps properly. Of course, spring isn't your only
option. You can use other open source alternatives that do something
similar, but Spring is by far the best one available. I don't know what to
say. Just read it and spend a day or two learning it. It really isn't that
hard and you'll definately see the advantages compared to your old code. Of
course, if you have no multi-tiered apps to compare it with, I can see why
you wouldn't get it.

So 'fess up: are you the new official (unoffical) spokesperson for
spring? You've "sprung up" (excuse the pun) from nowhere (save
Seattle) within the last few days, singing the praises of this
particular framework. You've posted technically incorrect information
and not responded to enquiries other than to claim that everything
you've said is correct. You use a non-existent domain as part of
your e-mail address in posts.
Are you a member of the development team? Did you get some special
dispensation for flooding the ng with good words? That's all fine as
long as you acknowledge any connections. A disclaimer can be so very
helpful...
[Please don't warn me about feeding the trolls...]
 
J

Job Numbers

Sudsy said:
Job Numbers wrote:
Just read the docs before making all of these assumptions. Odds are, if
you have never used a light-weight container using dependany injection,
you aren't writing large scale apps properly. Of course, spring isn't
your only option. You can use other open source alternatives that do
something similar, but Spring is by far the best one available. I don't
know what to say. Just read it and spend a day or two learning it. It
really isn't that hard and you'll definately see the advantages compared
to your old code. Of course, if you have no multi-tiered apps to compare
it with, I can see why you wouldn't get it.

So 'fess up: are you the new official (unoffical) spokesperson for
spring? You've "sprung up" (excuse the pun) from nowhere (save
Seattle) within the last few days, singing the praises of this
particular framework. You've posted technically incorrect information
and not responded to enquiries other than to claim that everything
you've said is correct. You use a non-existent domain as part of
your e-mail address in posts.
Are you a member of the development team? Did you get some special
dispensation for flooding the ng with good words? That's all fine as
long as you acknowledge any connections. A disclaimer can be so very
helpful...
[Please don't warn me about feeding the trolls...]

Yeah, I'm Rod Johnson!

Seriously, I just use it for everything. I can't imagine going back because
that would make my life harder. Life should be hard, but not crazy hard.
Spring makes it simpler. If xyz would make my life simpler, I'd be praising
that too. Sorry for wanting to make people's life simpler. Enjoy bloated
ejb. I hope your software looks like a big whale when it's finished.
 
S

Sudsy

Job Numbers wrote:
Yeah, I'm Rod Johnson!

Seriously, I just use it for everything. I can't imagine going back because
that would make my life harder. Life should be hard, but not crazy hard.
Spring makes it simpler. If xyz would make my life simpler, I'd be praising
that too. Sorry for wanting to make people's life simpler. Enjoy bloated
ejb. I hope your software looks like a big whale when it's finished.

Actually, my code is more like a penguin, sleek and fast (helps that
it runs on Linux). Did you offer your superior consulting experience
to the other poster as I suggested?
EJBs have applicability to certain classes of problems, like it or
not. Ignoring reality doesn't make it go away. I agree that J2EE is
not the be-all, end-all solution but then neither is the platform
you espouse.
I'll continue to use the tools I find most appropriate for particular
situations. I discovered that ant can be a powerful backup tool, for
example. Always learning...
 
A

Alex Polite

Spring is a framework that makes writing J2EE applications a lot easier.
It's not a "lock-me-in" framework since it's very simple and very light, and
all of it works on interfaces. This means you can just implement a new
interface, swap out the old component for your new one. Just read the
reference documentation. You don't have to read the whole thing, just get
your feet wet with the bean factories. I don't know how anyone could
develop without dependancy injection nowadays.

<!-- DATASOURCE -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property
name="driverClassName"><value>org.postgresql.Driver</value></property>
<property
name="url"><value>jdbc:postgresql://localhost:5432/databasename</value></property>
<property name="username"><value>username</value></property>
<property name="password"><value>password</value></property>
</bean>

Isn't this what commons dbcp does with jocl? Without all the framwork hullabalo.

alex
 
J

Job Numbers

Roedy Green said:
What's the difference between what you do in Spring and using property
files?

Why even write the properties file code? And this isn't just properties.
This sets your beans for you, it makes them to singletons or not, it
autowires beans to other beans, etc. You are just missing out in all the
features it gives you and this is just one of the packages of a very rich,
light-weight model. Also everything uses the same configuration management,
so you don't have each layer or component configuring itself.

Once you know how to setup spring's bean factories, it takes maybe 20
minutes to it up for your entire project. Rewrite the wheel if you want,
but this is very light-weight. It's definately not a case for bloat.
 
R

Roedy Green

Once you know how to setup spring's bean factories, it takes maybe 20
minutes to it up for your entire project. Rewrite the wheel if you want,
but this is very light-weight. It's definately not a case for bloat.

I have several general reluctances about using such beasts:

1. will they be around? Will I end up holding the bag with code no
longer supported?

2. will it interfere with other tools?

3. will taking the time to learn it be worth the time saved?

4. would I be better off with something whose code I can modify. So
often an author refuses to fix something that drives you nuts you know
you could fix yourself in a day.

5. Will the free code turn into pay code with onerous licensing? Is
this really just a come on to suck me in?
 
C

Christophe Vanfleteren

Roedy said:
I have several general reluctances about using such beasts:

1. will they be around? Will I end up holding the bag with code no
longer supported?

This is a risk you take with any third party library.
The opensource nature of Spring (Apache Licensed) negates a great deal of
this risk.
2. will it interfere with other tools?

Spring doesn't, in fact, it works very well with other products. for
example, it has excellent support for Hibernate, JDO, IBatis, JSP,
Velocity, Tapestry, ...
It really makes working with those projects a lot easier.
It is also very non intrusive, since you still write "normal" java code.
3. will taking the time to learn it be worth the time saved?

In Spring's case, that is definitely the case. Instead of coding all kinds
of factories and singletons, you just define them once in an xml file.
Want to swap out some components for testing? Just change the file, no need
for recompilation.
4. would I be better off with something whose code I can modify. So
often an author refuses to fix something that drives you nuts you know
you could fix yourself in a day.

Since Spring is Apache licensed, this is a non sequitur.
5. Will the free code turn into pay code with onerous licensing? Is
this really just a come on to suck me in?

Also extremely unlikely, since lots of different developers are
contributing, who do not depend on Spring itself for their income. Getting
all of them to agree on a license change would be very difficult. And the
original code would still be available to you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top