Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to design for JPA in a non-Java EE web server (e.g. Tomcat)
    primarykey
    data
    text
    <p>Considering there is no @PersistenceContext available to inject the EntityManager, plus you need to manually manage Transactions, what is the best way to design such an application?</p> <p>For the EntityManagerFactory/EntityManager, as far as I can see, you must have each DAO accepting an EntityManager in the costructor e.g.</p> <pre><code>public class DAOImpl implements DAO { private EntityManager em; DAOImpl(EntityManager em){ this.em = em; } //all CRUD operations follow } </code></pre> <p>The first question that rises is when do you call <em>EntityManager#close()</em>?</p> <p><strong>Point A:</strong> The way I see it, you are better off doing this in a <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html" rel="nofollow noreferrer">Filter</a> at the end of the request cycle, which implies that you associate the EntityManager with the current thread (using ThreadLocal?)</p> <p>Second question is, how and when do you inject the EntityManager?</p> <p>Considering there is a <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextListener.html" rel="nofollow noreferrer">ServletContextListener</a> where we create and close the EntityManagerFactory, we could have a static method as follows</p> <pre><code>public static EntityManager createEntityManager(){ return entityManagerFactory.createEntityManager(PERSISTENT_NAME); } </code></pre> <p>but since we want to encapsulate creating the DAO, we could use a factory e.g.</p> <pre><code>public class DAOFactory { public static DAO dao(){ //return a new DAO } } </code></pre> <p>As per <strong>Point A</strong> we should use a ThreadLocal to create the DAO using the EntityManager for the current Thread.</p> <p>For managing Transactions.</p> <p>The best way I can think of (which mimics the JPA spec) is to create your own Transaction annotation and use reflection to inject the begin/commit/rollback operations.</p> <p>You should then return a <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html" rel="nofollow noreferrer">Proxy</a> from the DAOFactory which handles the transactions</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload