DAO and Service layer in Spring: session management
Am I right in understanding the principles of DAO & Service layer interconnection? DAO performs extractions of base objects, say by id from a db.
Servi开发者_开发知识库ce layer USES a DAO object and may invoke MORE THAN ONE METHOD of DAO in one function. So, Service layer has to:
instantiate a DAO implementation object
invoke as many methods of the DAO as needed
If a Dao implements an interface, then does a DAO interface has to have a method setSessionFactory()
?
How to declaratively mark in Spring:
DAO object
Service layer methods, and class as a whole
so that it would give what is needed?
I'm surprised no one else has specifically mentioned this, but an implementation-specific detail such as setSessionFactory()
should not be in your DAO interface. By adding a Hibernate-specific class to your DAO interface, you are tying your DAO's directly to Hibernate.
The purpose of using interfaces and dependency injection is to allow you to change an implementation detail (such as, what ORM solution you use, or if your data comes from a web service vs a database) of a layer (your DAO) without affecting other layers.
If you add setSessionFactory
to your DAO interface, then all other layers that use this DAO become aware and tied to the fact that the data access is done through Hibernate. This is the direct opposite of what you are trying to achieve by using interfaces and dependency injection.
For my projects I write a base class which has a setSessionFactory()
method that all my DAOs extend. Then I wire up my DAOs with Spring so that it injects the SessionFactory
into each DAO.
Hibernate has a SessionFactory.getCurrentSession()
so if you inject the SessionFactory
into your DAOs and use that method, then the scope of the Session
will be defined according to your transaction management mechanism.
What this means is if you have a method as such:
@Transactional
public void doSomething(){
dao1.makeCall();
dao2.makeOtherCall();
}
The SessionFactory
you inject into each DAO when constructed will be using the same Session
. But only for the scope of that transaction.
- Leave transaction and session management to spring (via the built-in transaction managers).
- In your DAOs use
sessionFactory.getCurrentSession()
tp access the session - have the
SessionFactory
injected in the DAO. - have DAO in scope
singleton
- use declarative transactions (either with
<aop
or with@Transactional
) - the DAO is injected into the service objects via a regular dependency-injection. The same way the service classes are injected where they are needed.
精彩评论