users@jersey.java.net

Re: [Jersey] Jersey and JPA best practices?

From: Florian Hars <hars_at_bik-gmbh.de>
Date: Mon, 22 Dec 2008 12:12:52 +0100

Paul Sandoz schrieb:
> Complete injection support equivalent to that on Servlet is not
> currently implemented.

That might explain why it didn't work :-). Anyway, what are the thread
safety properties of jersey resources? Would it even be useful to inject
an EntityManager or would you run into concurrency issues?

> What servlet class are you using for your web application?

Ah, that is the secret sauce, you have to use
com.sun.jersey.server.impl.container.servlet.ServletAdaptor
instead of
com.sun.jersey.spi.container.servlet.ServletContainer
if you want it to give you an EntityManagerFactory.

Maybe somebody should add an item to the FAQ that explains the following
points:

1. You must use the mentioned ServletAdaptor class.
2. You must specify the persistence unit as an init-param
   to the servlet.
3. You can only inject via @PersistenceUnit EntityManagerFactory emf = ...
4. How to use EntityManagers created by that Factory to avoid
   threading problems in your jersey resources
5. How to use transactions in jersey resouces.
(have I missed anything?)

The answers are all implicit in the bookmarks example, but it might help
people if they are written down with some short explanations.

- Florian.

PS: Koan for today:
After making the change, the glassfish first gave me:

java.lang.ClassCastException: com.example.jpa.User cannot be cast to com.example.jpa.User

After playing around and finally redeploying the same code,
everything works. Classloader madness?