This solution replaces ThreadLocal Session pattern and greatly
simplifies session management.
/**
* An interface which has to be implemented
* by every class which is needed a session for the
* operation.
* Actually the method of it is implemented in the aspect
* therefore there no need to add any method to the parent
* class
*
* @author Renat Zubairov
*/
public interface SessionHolder
{
public abstract Session getSession();
}
/**
* Aspect for Session management.
* Manages session and open it as soon as it was requested
* from any of the Controllers (objects realizes SessionHolder
interface)
* Closes session after controllers are worked out.
*
* @author Renat Zubairov
*/
public aspect SessionManagementAspect percflow (execution(*
SessionHolder+.*(..)) && !cflowbelow(execution(* SessionHolder+.*
(..)))) {
private Session s = null;
public Session getSession() {
if (s == null) s = SessionFactory.getInstance().getSession();
return s;
}
public void closeSession() {
if (s != null) s.close();
}
private pointcut pc(): execution(* SessionHolder+.*(..));
public Session SessionHolder.getSession() {
return SessionManagementAspect.aspectOf().getSession();
}
after() : pc() && !cflowbelow(pc()) {
SessionManagementAspect.aspectOf().closeSession();
}
}
Explanations: All classes which needs an access to the
HibernateSession implements interface SessionHolder (it can be done
manyally or via connector aspect using declare parrents: * implements
SessionHolder). This type of introduction called Container
Introduction (copyright by Stefan Hannenberg from Uni-Essen) or
Abstract Schema (copyright by Rickard Oberg). Althroug interface has
one method this method is implemented by aspect therefore classes
which needs a session needn't to implement method getSession().
To get a session in the worker classes all you need to do is:
((SessionHolder)this).getSession();
Session will be automatically opened as soon as requested and
propogated in the current thread (controlflow). It will be also closed
as soon as controllflow will ends (i.e. execution of the first called
SessionHolder completed). |