Last active
August 29, 2015 14:04
-
-
Save dilnei/ff718a0792e4377a1a7f to your computer and use it in GitHub Desktop.
TransactionInterceptor
This file contains 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
package br.com.weblog.interceptor; | |
import javax.inject.Inject; | |
import javax.interceptor.AroundInvoke; | |
import javax.interceptor.Interceptor; | |
import javax.interceptor.InvocationContext; | |
import javax.persistence.EntityManager; | |
import org.apache.log4j.Logger; | |
/** | |
* Interceptador que ira receber uma EntityManager via Injeção de dependências | |
* da CDI. | |
* | |
* @author Dilnei Cunha. | |
*/ | |
@Interceptor | |
@Transactional | |
public class TransactionInterceptor { | |
Logger logger = Logger.getLogger(TransactionInterceptor.class); | |
@Inject | |
private EntityManager entityManager; | |
/** | |
* Método que inicia a transação, este é o método que interceptara as | |
* requisições. | |
* Como nossa classe não implementa nenhuma interface podemos | |
* atribuir qualquer nome para o método para indicar que é ele que | |
* interceptará as invocações, precisamos anotar com @AroundInvoke. | |
* | |
* @param context | |
* @return | |
* @throws Exception | |
*/ | |
@AroundInvoke | |
public Object intercept(InvocationContext context) throws Exception { | |
logger.info("Abrindo a Transação"); | |
entityManager.getTransaction().begin(); | |
Object resultado = null; | |
// Passando para o JSF tratar a requisicão e pegando o retorno da lógica. | |
try { | |
resultado = context.proceed(); | |
logger.info("comitando a Transação"); | |
entityManager.getTransaction().commit(); | |
} catch (Exception exception) { | |
entityManager.getTransaction().rollback(); | |
logger.warn("rollback a Transação"); | |
throw exception; | |
} | |
return resultado; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment