Created
May 5, 2011 15:55
-
-
Save rodolfoliviero/957304 to your computer and use it in GitHub Desktop.
Override default vraptor HibernateTransactionInterceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import br.com.caelum.vraptor.Intercepts; | |
import br.com.caelum.vraptor.Validator; | |
import br.com.caelum.vraptor.core.InterceptorStack; | |
import br.com.caelum.vraptor.http.MutableResponse; | |
import br.com.caelum.vraptor.interceptor.Interceptor; | |
import br.com.caelum.vraptor.resource.ResourceMethod; | |
import org.hibernate.Session; | |
import org.hibernate.Transaction; | |
@Intercepts | |
public class HibernateTransactionInterceptor implements Interceptor { | |
private final Session session; | |
private final Validator validator; | |
private final MutableResponse response; | |
public HibernateTransactionInterceptor(Session session, Validator validator, MutableResponse response) { | |
this.session = session; | |
this.validator = validator; | |
this.response = response; | |
} | |
@Override | |
public void intercept(InterceptorStack stack, ResourceMethod method, Object instance) { | |
addRedirectListener(); | |
Transaction transaction = null; | |
try { | |
transaction = session.beginTransaction(); | |
stack.next(method, instance); | |
if (!validator.hasErrors() && !transaction.wasCommitted()) { | |
transaction.commit(); | |
} | |
} finally { | |
if (transaction != null && transaction.isActive()) { | |
transaction.rollback(); | |
} | |
} | |
} | |
private void addRedirectListener() { | |
response.addRedirectListener(new MutableResponse.RedirectListener() { | |
@Override | |
public void beforeRedirect() { | |
if (!validator.hasErrors() && session.getTransaction().isActive()) { | |
session.getTransaction().commit(); | |
} | |
} | |
}); | |
} | |
public boolean accepts(ResourceMethod method) { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment