views:

196

answers:

2

I am writing a module that will be used in different applications (2-tiers and 3-tiers). I'll need to connect to a DB. so, I made the module requires a java.sql.Connection object as a parameter when used with a 2-tier application. there's no problem there.

the problem i'm facing is that in case of a 3-tier application, the module will be used from the Presentation tier and as such, I don't want to give the module a Connection object for DB access.

What do you suggest I use to solve this problem ?

A: 

Your instinct to pass a Connection to the persistence object is a good one, as is your reluctance to make the presentation tier responsible for acquiring it.

I'd recommend reading about the MVC pattern and looking into Spring. The Spring idiom will show you the proper way to layer an application. It'll help with your dependency issues as well.

UPDATE:

You'll have to read more about Spring.

Using Spring's common idiom of web->service->persistence interface layering will help layer your app properly.

Spring has dependency injection to help you manage your dependencies.

Spring's framework classes help you with acquiring and managing things like database connections.

I'm arguing that it makes little sense for you to rewrite what someone else has already written better. I'm suggesting that you start by browsing through Spring MVC Step By Step to see if you agree.

If you'd rather not learn Spring, I'd advise you to at least look at the classes they wrote for DataSource and JDBC connections. Maybe you can improve the way you're doing yours by looking at theirs.

duffymo
Thanks, I'm currently reading the MVC pattern but I don't understand how it would help me in this particular case. it does seem to help separate responsibilities within my app and helps decouple stuff.but I still can't figure out how to solve my problem.
Attilah
Read about Spring. It's already solved your problem.
duffymo
@ duffymo, Could you please be more specific, please ?
Attilah
@Attilah, see my update. You'll have to put some effort in here if you'd like to find out about Spring.
duffymo
A: 

In Spring you define an application context which is in most cases just an XML file, and that contains a number of appliction object called beans.

<bean id="myDbConnection" scope="prototype" class="...">
   ...
</bean>

<bean id="myPersistanceManager" class="my.application.PersistanceManager">
   <property name="connection" ref="myDbConnection" />
</bean>

myDbConnection is a bean defined in the same application context and that contains all connection details.

Then in your presentation layer you just use applicationContext.getBean("myPersistance") and you get an instance of your persistance manager initialised with all dependecies. And you can have different application contexts for different deployment options.

Superfilin