openjpa-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Edoardo Panfili <edoa...@aspix.it>
Subject Re: how to count sub-elements without retrieving them?
Date Wed, 25 Mar 2009 17:48:03 GMT
Paul Copeland ha scritto:
> Hi Edoardo -
> 
> This is a bit off the topic of your question, but I am interested in 
> your pattern for setting the EntityManager in a filter.  That seems like 
> a reasonable thing to do.  I wonder if other servlet developers on the 
> list do it any other way?
> 
> One question I have for you is that doFilter() throws ServletException 
> and IOException.  Don't you have to declare those in the signature?  And 
> lastly, it would be a good practice to put entityManager.close() in a 
> finally clause.
yes, the I cut down too much of the code.

You are right regarding try/finally block I am going to modify my code:
---------------------------------------------------
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ManagerJpa implements Filter{

   EntityManagerFactory entityManagerFactory;
   public void init(FilterConfig arg) throws ServletException {
     entityManagerFactory =
         Persistence.createEntityManagerFactory("openjpa-habitat");
   }

   public void destroy() {
   }

   public void doFilter(ServletRequest req, ServletResponse res,
       FilterChain chain) throws IOException, ServletException {

     EntityManager entityManager = null;
     entityManager = entityManagerFactory.createEntityManager();
     req.setAttribute("em", entityManager);
     try {
       chain.doFilter(req,res);
     } finally{
       entityManager.close();
     }
   }
}
---------------------------------------------------

Edoardo



Mime
View raw message