Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to have singleton DAO objects?

Tags:

java

spring

dao

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)

like image 766
Ada Avatar asked Oct 14 '10 21:10

Ada


People also ask

Should DAO be singleton?

It is better to create a single instance of your DAO and pass it into the constructor of classes that need it. I tend to avoid singletons whenever I can, because amongst other things, they make your code difficult to test and hide dependencies.

Why should you avoid singletons?

By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.

How can we avoid singleton class?

There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw a run-time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.

Can you destroy a singleton object?

You cannot destroy an object, only the JVM can do that. Once an object is inaccessible by any live threads, it then becomes eligible for garbage collection. Sounds like something which possibly shouldn't be a Singleton.


1 Answers

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#beans-factory-scopes-prototype

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.

like image 181
hvgotcodes Avatar answered Sep 18 '22 20:09

hvgotcodes