In JPA the Entities are nice annotated Plain Old Java Objects. But I have not found a good way to interact with them and the database.
In my current app, my basic design is always to have a sequence based id as primary key so I usually have to look up entities by other properties than PK.
And for each Entity I have a stateless EJB of
@Stateless public class MyEntApiBean implements MyEntApi { @PersistenceContext(unitName = 'xxx') @Inject EntityManager entityManager;
with query methods that all are some variation
/** * @return A List of all MyEnts that have some property * @param someProp some property */ public List<MyEnt> getAllMyEntsFromProp(final String someProp) { try { final Query query = entityManager.createQuery('select me from MyEnt me where me.someProp = :someProp'); query.setParameter('someProp', someProp); return query.getResultList(); } catch(final NoResultException nre) { log.warn('No MyEnts found'); } return new ArrayList<MyEnt>(); }
So:
-
I really hate having these methods in an EJB because they seem to belong with the entities themselves, and the EJB local interfaces annoy the crap out of me.
-
I hate the duplication that I have in each method with ‘try, createQuery, getResultList,catch, log, return’ (mostly a consequence of no closures or ‘with statement’ or somesuch in Java).
Does anyone have a suggestion for a better way to interact with the Entities and Database that addresses one or both of my issues?
I am currently thinking of doing some base methods with generics and reflection to get some generic query methods to reduce the duplication (issue 2) (I will put a prototype up for review later).
Thanks, Anders
Try Seam. The Query Objects do most of the work for you, and they’re easily extendable. Or, you could always implement a similar pattern.
In general, Seam does a lot of useful stuff to bridge the gap between JPA and you view and business layers. You don’t have to use JSF for Seam to be useful.