Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.databases > #508

JPA Style question

From "Jeffrey H. Coffield" <jeffrey@digitalsynergyinc.com>
Newsgroups comp.lang.java.databases
Subject JPA Style question
Date 2011-11-20 10:07 -0800
Organization A noiseless patient Spider
Message-ID <jabfkq$lg1$1@dont-email.me> (permalink)

Show all headers | View raw


I am trying to establish a style for using JPA for Java project we will 
use for ourselves and our customers.

Most of the examples I see for getting an entity using JPA look like this:

         EntityManagerFactory emf =
               Persistence.createEntityManagerFactory("MTestPU");
         EntityManager em = emf.createEntityManager();

         Query q = em.createNamedQuery("Mxaccount.findByAccount");
         q.setParameter("account", "123");

         Mxaccount acct = (Mxaccount) q.getSingleResult();
         String user = acct.getUsername();

What seems to make more sense to me would be :

         Mxaccount acct = MxaccountWrapper.getAccount("123");
         String user = acct.getUsername());

where the following class has been added:

public class MxaccountWrapper {
     public static Mxaccount getAccount(String accountNumber) {
         EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("MTestPU");
         EntityManager em = emf.createEntityManager();

         Query q = em.createNamedQuery("Mxaccount.findByAccount");
         q.setParameter("account", accountNumber);

         return (Mxaccount) q2.getSingleResult();
     }
}

This has the following advantages:

1. Getting a Mxaccount will occur many times so this is better code reuse.

2. Creating the EntityManagerFactory repeatedly is more error prone as 
you have to use the persistence unit name and know the query parameters 
and many errors here are run time errors and not compile time errors.

3. If a parameter is added to a query later, adding the parameter to the 
getAccount method leads to compiler errors in the classes that call it 
and that shows up in an IDE and are easy to find.

Thanks,

Jeff Coffield
www.digitalsynergyinc.com

Back to comp.lang.java.databases | Previous | Next | Find similar


Thread

JPA Style question "Jeffrey H. Coffield" <jeffrey@digitalsynergyinc.com> - 2011-11-20 10:07 -0800

csiph-web