tags:

views:

102

answers:

2

Consider the following classes' structure:

  1. BaseDAO with methods to crest PreparedStatement and get connection from pool
  2. AccountDAO extends BaseDAO to work with Account table via JDBC. This class is singleton
  3. AccountService witch calls methods of AccountDAO like this: AccountDAO.getInstance().login(name, password).

AccountDAO is a Spring bean with @Transactional annotations to methods that insert some data.

Is this OK? I think singleton DAO classes can cause performance problems. May be it is better to use some spring injections into service layer classes? (I'm new to Spring, so any advice will be appriciated)

+8  A: 

The recommended approach in the Spring documentation is to write your DAOs as normal classes and use the singleton scope. This will work fine if your DAOs maintain no state.

http://static.springsource.org/spring/docs/2.0.x/reference/beans.html

section 3.4.2.

If you are using Spring, you shouldn't need to deal with prepared statements and whatnot, unless you are doing something wonky. Look at JdbcTemplate or HibnerateTemplate. Yes, you should wire Spring to inject your DAOs into your services or wherever you need to use them.

hvgotcodes
A: 

I am not too familiar with Spring but in general you don't want the connections to your data sources to be accessed from multiple threads. It is probably O.K. if you configure it so thatt the DAO objects are pseudo-singletons within a thread context but are not shared across threads. Most IoC containers will allow you to do this through configuration.

Of course, this brings other considerations about data consistency into play and you have to manage those carefully. Generally the ORM part will help you with that though.

ale