PDA

View Full Version : Singleton or not to singleton in DAO´s ?!



barbosa
Feb 23rd, 2005, 11:26 AM
Hello all !

My doubt is about singletons and or prototypes.

1) Simple domain objects(beans) should always be prototypes ?!
2) DAO´s should be prototype too ?!

An example:
Suppose i have a userDAO and a "save method" defined with propagation_required.
That must run within a existing transaction otherwise it will start a new one.
Ok.
If the DAO is singleton , when two diferent people call the "save method" it will share the same DAO, then the transaction too !?


3)Propagation_required works like this !?

methodA () { doSomething() -> starts a new transaction
doOther() -> uses the same transaction !?
}
!

dhewitt
Feb 23rd, 2005, 11:55 AM
Hi,

To answer your points:

1) I find that almost everything you wire up with an application context should be a singleton, unless there is a good reason not to do so.
2) Your dao should definitely be a singleton. When two people call the singleton dao, a different transaction operates on each thread of execution.
3) A transaction starts and ends at the method boundary. If methodA is PROPAGATION_REQUIRED, then both doSomething() and doOther() will operate in the same transaction. If doSomething() and doOther() have separately had PROPAGATION_REQUIRED applied, then they will begin and commit separate transactions in turn.

Cheers,
-Dave

Martin Kersten
Feb 23rd, 2005, 01:00 PM
I usally dont like the singleton approach, but with spring singleton is a matter of declaration not a matter of implementation. So you leave the question wether it is a singleton from the implementation to the usage. This makes sense since it is completely transparent to the implementation.

Use a singleton and like dhewitt said it, the dao implementation uses a ThreadLocal implementation so every thread uses a diffrent connection/session. (depending on which DAO you use).

Cheers,

Martin (Kersten)