rd22 February 2016

How to access web layer(Controllers) from the DAO Layer?

I had to cancel the running queries. In my DAO I set the Entity.session in the ServletContext when I start the query and remove it when the query is finished. Then check in the Controller if the session is present in the ServletContext, if it is present then I cancel the query by calling the session.cancelQuery() from the session object in the ServletContext.

This was working fine in my dev environment, but in my pre-prod testing the entire code does not run inside the tomcat container. The web part runs in tomcat whereas the data layer runs a java application. hence I could not find the ServletContext in the DAO class and it gave me a ClassNotFound Exception

So I decoupled the web layer in the DAO. Now I set the hibernate.session in the controller itself when it calls the DAO calculate(). But this created a problem, now the session exists even if there are no calculations going on and in actual there are some post or precalculations. And my mechanism to cancel the query doesn't work.

So what I need is a way to access the Controller from the DAO to set the session. I could have used a static method in the Controller and then set the session from it but I think this is again not a good practice.

DAO initial Code:

public calculate(){
Session session = mEntityManager.unwrap(Session.class);
//pre possing                   
if(session != null)
{
    mContext.setAttribute(""+view.getId(), session);
}
List<Object[]> results = query.getResultList();
mContext.removeAttribute(""+view.getId());
//post processing
}

Decoupled DAO code: The method getSession() is called from the controller before the calculate method is called in the controller. And then when the user requests a cancel from the UI the cancel method is called in the control

Answers


Raedwald February 2016

It seems you have convoluted control flow because you are not properly separating detection of a problem from handling the problem: you detect a problem in the data layer but need to handle it in the presentation layer.

Consider using exceptions. Have the data layer throw an exception when it detects a problem. The presentation layer can handle problems in the data layer by catching exceptions.

Post Status

Asked in February 2016
Viewed 1,714 times
Voted 11
Answered 1 times

Search




Leave an answer