Monday, January 12, 2015

STRUTS2 Interceptor to manage Hibernate Transcation

package com.raj.nvsmx.pd.controller.interceptor;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.raj.commons.logging.LogManager;
import com.raj.nv.pd.constants.Results;
import com.raj.nv.pd.model.HibernateSessionFactory;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * @author kirpalsinh.raj
 * This Interceptor class is used to begin/commit/rollback Hibernate session transaction as per the result returned from the action classes. 
 * 
 */

public class TransactionInterceptor extends BaseInterceptor {

private static final long serialVersionUID = 1L;
private static final String MODULE = TransactionInterceptor.class.getSimpleName();

Transaction transaction = null;
Session session = null;
String actionName;

@Override
public String intercept(ActionInvocation parentActionInvocation) throws Exception {

try {
 
session = HibernateSessionFactory.getSession();
transaction = session.beginTransaction();
actionName = parentActionInvocation.getProxy().getActionName();

parentActionInvocation.addPreResultListener( new PreResultListener() {
@Override
public void beforeResult(ActionInvocation childActionInvocation, String result) {
if (transaction != null && Results.SUCCESS.equalsIgnoreCase(result)) {
transaction.commit();
LogManager.getLogger().info(MODULE,"Transaction committed successfully for action "+actionName);
} else {
rollbackTranscation();
}
}
});

return parentActionInvocation.invoke();

} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Transaction Failed for action "+actionName+". Reason: " + ex.getMessage());
rollbackTranscation();
return Results.ERROR;

} finally {
closeSession();
}
}

public void rollbackTranscation(){
LogManager.getLogger().warn(MODULE,"Rollback Transaction for action "+actionName);
try {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
} catch (Exception ex) {
LogManager.getLogger().error(MODULE,"Failed to Rollback Transaction for action "+actionName+". Reason: " + ex.getMessage());
}
}

public void closeSession(){
try {
if (session != null) {
session.close();
}
} catch (HibernateException ex) {
LogManager.getLogger().error(MODULE,"Failed to close Session for action "+actionName+". Reason: " + ex.getMessage());
}
}
}


Keep Visiting :)
Write your comment buddy

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...