Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

PersistenceFilter

By: a guest on Mar 9th, 2011  |  syntax: Java  |  size: 1.42 KB  |  hits: 54  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public class PersistenceFilter implements Filter
  2. {
  3.     protected static final Logger log = Logger.getLogger(PersistenceFilter.class.getName());
  4.     private EntityManagerFactory factory;
  5.  
  6.     @Override
  7.     public void init(FilterConfig filterConfig) throws ServletException
  8.     {
  9.         factory = Persistence.createEntityManagerFactory("mydb");
  10.     }
  11.  
  12.     @Override
  13.     public void destroy()
  14.     {
  15.         factory.close();
  16.     }
  17.  
  18.     @Override
  19.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
  20.     {
  21.         EntityManager em = factory.createEntityManager();
  22.         ThreadLocalEntityManager.set(em);
  23.  
  24.         EntityTransaction tx = em.getTransaction();
  25.         tx.begin();
  26.  
  27.         try
  28.         {
  29.             chain.doFilter(req, res);
  30.             tx.commit();
  31.         }
  32.         catch (Exception e)
  33.         {
  34.             tx.rollback();
  35.         }
  36.         finally
  37.         {
  38.             log.info("closing EntityManager: " + EMF.entityManager());
  39.             em.close();
  40.         }
  41.  
  42.     }
  43. }
  44.  
  45.  
  46.  
  47.  ThreadLocalEntityManager
  48. {
  49.     private static ThreadLocal<EntityManager> holder = new ThreadLocal<EntityManager>();
  50.  
  51.     private ThreadLocalEntityManager()
  52.     {
  53.     }
  54.  
  55.     public static EntityManager get()
  56.     {
  57.         return holder.get();
  58.     }
  59.  
  60.     public static void set(EntityManager em)
  61.     {
  62.         holder.set(em);
  63.     }
  64.  
  65. }