@Override public void beforePhase(PhaseEvent event) { logger.debug("In beforePhase"); if (event.getPhaseId().equals(PhaseId.RESTORE_VIEW)) { FacesContext context = event.getFacesContext(); PortletRequest request = (PortletRequest) context.getExternalContext().getRequest(); ContextUtils.exposeRequest(request); JpaUtils.exposeEntityManager(request); } }
@Override public void afterPhase(PhaseEvent event) { logger.debug("In afterPhase"); FacesContext context = event.getFacesContext(); if (event.getPhaseId().equals(PhaseId.RENDER_RESPONSE) || context.getResponseComplete() || (!event.getPhaseId().equals(PhaseId.RESTORE_VIEW) && context.getRenderResponse())) { PortletRequest request = (PortletRequest) context.getExternalContext().getRequest(); JpaUtils.unexposeEntityManager(request); ContextUtils.unexposeRequest(request); } }
/** * expose the JPA Entity Manager to the current thread * @param request */ public static void exposeEntityManager(PortletRequest request) { //use code form doFilterInternal of Spring OpenEntityManagerInViewFilter EntityManagerFactory emf = getEntityManagerFactory(); request.setAttribute(REQUEST_JPA_ENTITY_MANAGER_ATTRIBUTE, emf); Boolean participate = false; if (TransactionSynchronizationManager.hasResource(emf)) { participate = true; } else { logger.debug("Opening JPA EntityManager in exposeEntityManager"); try { EntityManager em = emf.createEntityManager(); TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } request.setAttribute(REQUEST_JPA_PARTICIPATE_ATTRIBUTE, participate); }