Using a JDBC Connection from the Presentation Tier in Two-Tier and Three-Tier Applications

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

the problem I am facing is that in the case of a 3 tier application the module will be used from the Presentation tier and as such I do not want to provide the module with a Connection object to access the DB.

What do you propose to use to solve this problem?

+2


source to share


2 answers


In Spring, you define an application context, which in most cases is just an XML file and contains a series of application objects 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 containing all the connection information.

Then in your presentation layer, you simply use applicationContext.getBean ("myPersistance") and you will get an instance of your persistence manager initialized with all dependencies. And you can have different application contexts for different deployment options.

+1


source


Your instinct to hand off a connection to a persistence object is good, as is your unwillingness to make the presentation layer responsible for acquiring it.

I would recommend reading about the MVC pattern and looking into Spring. The Spring idiom will show you the right way to fold your application. It will also help with your addiction problems.

UPDATE:

You need to learn more about Spring.

Spring's use of the common idiom web interface> service-> persistence will help you stack your application correctly.



Spring has dependency nesting to help you manage your dependencies.

Class classes

Spring helps you acquire and manage things like database connections.

I submit that you don't need to rewrite what someone else has written better. I suggest you start by looking at Spring MVC Step by Step to see if you agree.

If you prefer not to learn Spring, I would suggest that you at least take a look at the classes they wrote for DataSource and JDBC connections. Perhaps you can improve the way you do by looking at them.

0


source







All Articles