DAO As Stateless EJB vs. Plain Java Class
I'd like to get opinions on whether it makes more sense to implement a DataAccessObject (DAO) as a Stateless Session EJB or as a plain Java class. I'd prefer to implement it as a plain Java class as there is less overhead to create such an object and to locate it. As long as the connection to the database comes from a pool (as opposed to each instance of the class having its own connection), I believe this approach should be better. Does anyone have any comments on this?
Actually, I am now leaning towards making my DAO a stateless EJB. The reason being that if I make it a class then each client will need to instantiate their own copy. It I make it an EJB, then I can have several available in the pool and they can be shared amongst the various clients. Considering that any method invocation within the DAO will have a short lifetime, I think this makes more sense than instantiating a DAO on a per client basis.
Making a DAO a SSB simply to get the benefit of automatic pooling is not a good enough reason.
A DAO which is a SSB is not a DAO anymore, but just a SSB accessing directly the Domain layer, which is bad design.
Also, consider (future ?) non-ejb clients. They too will need to access the DB through a DAO layer.
An Object Pool for DAO does not make much sense. DAO are lightweight objects, and certainly not a source of performance problems by themselves. The major source of performance concerns in J2EE apps are round-trips.
Pools make sense when the creation of an object takes a lot of time, like creating connections, and you have already the benefit of connection pooling with the DataSource object.
My opinion on the topic is to use both if needed. Write the DAO layer no matter what. If you need remoting, transactioning, and/or security, wrap the call to the DAO in an SSB. If it is not needed, call the DAO directly. These issues should not be a one size fits all solution for using one or the other.
As stated in the previous post, keep round trips to a minimum. Maybe wrap multiple DAO calls in the SSB. The network round trip to the DB will exist, but it can give you a good context for transactioning if needed.