Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.afs.web.common.struts.interceptor;
- import com.opensymphony.xwork2.ActionInvocation;
- import org.apache.struts2.interceptor.BackgroundProcess;
- import org.springframework.orm.jpa.EntityManagerFactoryUtils;
- import org.springframework.orm.jpa.EntityManagerHolder;
- import org.springframework.transaction.support.TransactionSynchronizationManager;
- import javax.persistence.EntityManager;
- import javax.persistence.EntityManagerFactory;
- /**
- * Used in conjunction with {@link OpenSessionExecuteAndWaitInterceptor}
- */
- public class OpenSessionBackgroundProcess extends BackgroundProcess {
- EntityManagerFactory entityManagerFactory;
- protected boolean initializationComplete;
- private Object lock = new Object(); // used for synchronization
- public OpenSessionBackgroundProcess(String name, ActionInvocation invocation, int threadPriority, EntityManagerFactory entityManagerFactory) {
- super(name, invocation, threadPriority);
- this.entityManagerFactory = entityManagerFactory;
- initializationComplete = true;
- synchronized (lock) {
- lock.notify();
- }
- }
- protected void beforeInvocation() throws Exception {
- while (!initializationComplete) {
- try {
- synchronized (lock) {
- lock.wait(100);
- }
- } catch (InterruptedException e) {
- // behavior ignores cause of re-awakening.
- }
- }
- EntityManager em = entityManagerFactory.createEntityManager();
- TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(em));
- super.beforeInvocation();
- }
- protected void afterInvocation() throws Exception {
- super.afterInvocation();
- EntityManagerHolder emHolder = (EntityManagerHolder)
- TransactionSynchronizationManager.unbindResource(entityManagerFactory);
- EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement