Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /* OpenEntityManagerInViewListener.java
  
   {{IS_NOTE
   Purpose:
   
   Description:
   
   History:
   Mon Dec 17 2007, Created by jeffliu
  }}IS_NOTE
 
  Copyright (C) 2006 Potix Corporation. All Rights Reserved.
 
  {{IS_RIGHT
  }}IS_RIGHT
  */
 
 package org.zkoss.zkplus.jpa;
 
 import java.util.List;
 
Listener to init and cleanup the JPA entityManager automatically

In WEB-INF/zk.xml, add following lines:


  <listener>
  <description>Hibernate "OpenEntityManagerInView" Listener</description>
  <listener-class>org.zkoss.zkplus.jpa.OpenEntityManagerInViewListener</listener-class>
 </listener>
 

Applicable to EJB version 3.2.ga or later

Author(s):
Jeff
Since:
3.0.2
 
 	private static final Logger log = LoggerFactory.getLogger(OpenEntityManagerInViewListener.class);
 	
 	//-- ExecutionCleanup --//
 	public void cleanup(Execution execExecution parentList errs)throws Exception
 		if(parent == null){
 			try
 			{
 				if (errs == null || errs.isEmpty()) {
 					.debug("JPA: Committing the database transaction: "+exec+" for entityManager:"+JpaUtil.getEntityManager());
 				}else
 				{
 					final Throwable ex = (Throwableerrs.get(0);
 					handleException(exec,ex);
 				}
 			}finally{
 				if(JpaUtil.getEntityManager().isOpen()){
 					.debug("JPA: close a database transaction: "+exec+" for entityManager:"+JpaUtil.getEntityManager());
 					JpaUtil.getEntityManager().close();
 				}else
 					.debug("JPA: the database transaction is not open: "+exec+" for entityManager:"+JpaUtil.getEntityManager());
 			}
 		}
 	}
 
 	//-- ExecutionInit --//
 	public void init(Execution execExecution parentthrows Exception {
 		
 		if(parent==null){
 			.debug("JPA: Starting a database transaction: "+exec+" for entityManager:"+JpaUtil.getEntityManager());
 		}
 	}

Default exception handler. This implementation simply rollback the transaction.

Application developer might want to extends this class and override this method to do other things like compensate for any permanent changes during the conversation, and finally restart business conversation... what can be done here depends on the applications design.

Parameters:
exec the execution to clean up.
ex the Throwable which is not handled during the execution
 
 	protected void handleException(Execution execThrowable ex) {
 		// Rollback only
 		rollback(execex);
 	}

rollback the current entityManager.

Parameters:
exec the execution to clean up.
ex the Exception being thrown (and not handled) during the execution
	private void rollback(Execution execThrowable ex) {
		try {
				.debug("Trying to rollback database transaction after exception:"+ex);
			}
catch (Throwable rbEx) {
			.error("Could not rollback transaction after exception! Original Exception:\n"+exrbEx);
		}
	}
New to GrepCode? Check out our FAQ X