Re: JPA in practice
Lew wrote:
Tom Anderson wrote:
Is there a convenient way to write code that gets an injected
EntityManager in a managed environment, but arranges its own provision
in an unmanaged one? Is that a meaningful thing to ask for?
I have a way, but I won't know if it works until I succeed at getting an
injected one. Then I can compare the two scenarios.
For the factory:
public class Persistuff
{
public static final String PUNIT = "projectPU";
@PersistenceUnit( unitName=PUNIT )
private static EntityManagerFactory emf;
private static final EntityManagerFactory EMFCANON =
Persistence.createEntityManagerFactory( PUNIT );
public static EntityManagerFactory getEmf()
{
return (emf == null? EMFCANON : emf);
}
}
For the manager:
<http://java.sun.com/javaee/5/docs/tutorial/doc/bnbrm.html#bnbrp>
public class Bizzniss
{
@PersistenceContext
private EntityManager em;
public void run()
{
EntityManager mgr = (em != null? em
: Persistuff.getEmf().getEntityManager());
// use 'mgr' here
}
}
Unknown: resource consumption and packratting caused by injected values,
if any.
I wouldn't bother to do the above, but in response to Tom's question the
above is what I would do. If that makes any sense. :-)
After all, there are no classpath issues - Java knows about the
annotations. All that happens, from observation, is that if in a given
situation that injection doesn't work then it doesn't work, and you
proceed and use the other approach(es).
My gut feeling is that if injection doesn't work then there's not much
penalty. For example, if your version of JSF doesn't support specific
annotations then nothing happens when you inadvertently use them.
I simply haven't bothered doing anything like the above because I never
write J2EE apps where it's not already known exactly what the
environment is. And if the environment ever changes there'll be major
advance notice.
Learning how to do this, I was running Glassfish 3 with a Postgres back
end, but my 4 GB RAM server box's power supply just gave up the ghost.
Turns out the combination of GF and PG with NetBeans was too much for my
poor single-core 64-bit workstation with only 1 GB RAM. Then I tried
the non-injective approach with Tomcat, Postgres and NetBeans. Turns
out that runs just great on the workstation.
That triggered a major "Hmmm." I may be on to a way to develop, deliver
and deploy full-blown custom apps very quickly with very low
administrative and hardware overhead.
Looks like JSF, JSP, JPA and servlets on Tomcat are a winning
combination. Once you factor in a few quirks.
(Bonus - Tomcat plays well with other environments like Apache Web
Server and many Java EE application servers.)
We ourselves (me and the other folks at the small consulting company I
work for) have internally arrived at much the same conclusion. As in,
why bother with a full-fledged app server when you don't need it?
To your list of API's/frameworks I would also add Seam as a
consideration, for some projects.
AHS