Advertisement
Guest User

OpenSessionBackgroundProcess

a guest
Jan 25th, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package com.afs.web.common.struts.interceptor;
  2.  
  3. import com.opensymphony.xwork2.ActionInvocation;
  4. import org.apache.struts2.interceptor.BackgroundProcess;
  5. import org.springframework.orm.jpa.EntityManagerFactoryUtils;
  6. import org.springframework.orm.jpa.EntityManagerHolder;
  7. import org.springframework.transaction.support.TransactionSynchronizationManager;
  8.  
  9. import javax.persistence.EntityManager;
  10. import javax.persistence.EntityManagerFactory;
  11.  
  12. /**
  13.  * Used in conjunction with {@link OpenSessionExecuteAndWaitInterceptor}
  14.  */
  15. public class OpenSessionBackgroundProcess extends BackgroundProcess {
  16.  
  17.     EntityManagerFactory entityManagerFactory;
  18.     protected boolean initializationComplete;
  19.     private Object lock = new Object(); // used for synchronization
  20.  
  21.     public OpenSessionBackgroundProcess(String name, ActionInvocation invocation, int threadPriority, EntityManagerFactory entityManagerFactory) {
  22.         super(name, invocation, threadPriority);
  23.         this.entityManagerFactory = entityManagerFactory;
  24.         initializationComplete = true;
  25.         synchronized (lock) {
  26.             lock.notify();
  27.         }
  28.     }
  29.  
  30.     protected void beforeInvocation() throws Exception {
  31.         while (!initializationComplete) {
  32.             try {
  33.                 synchronized (lock) {
  34.                     lock.wait(100);
  35.                 }
  36.             } catch (InterruptedException e) {
  37.                 // behavior ignores cause of re-awakening.
  38.             }
  39.         }
  40.         EntityManager em = entityManagerFactory.createEntityManager();
  41.         TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(em));
  42.         super.beforeInvocation();
  43.     }
  44.  
  45.     protected void afterInvocation() throws Exception {
  46.         super.afterInvocation();
  47.         EntityManagerHolder emHolder = (EntityManagerHolder)
  48.         TransactionSynchronizationManager.unbindResource(entityManagerFactory);
  49.         EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement