users@jersey.java.net

[Jersey] Transaction/EntityManager around serialization and field filtering

From: Martin Nedbal <martin_at_nedbal.net>
Date: Mon, 01 Jul 2013 00:36:12 +0200

Hi,
I have a non-EBJ application using JPA (Hibernate) and I wanted to give
access to part of it to external clients via REST API. There is Jetty
embedded (which is used for JWS already) and after simple configuration
I had it running (good job there, it is really simple to use!).

But I ran into huge issue with transaction handling (ie. EntityManager
availability). As this is non-EJB (nor any Spring-like framework
around), there is no @Transactional attribute or anything else (which
would not help anyway I guess). If one wants to do something in (JPA)
transaction, one has to call something like this:

Result result = Utils.runInTransaction(new Callable<Result>() {
  Result call() {
  ...


This works fine except for when there are some lazy fields.
Serialization of result is done later, maybe even in different thread
and there is no access to EntityManager (it was closed already) and if
there is an attempt by a getter to fetch some lazy fields, it obviously
crashes there.

Is there a way how to wrap whole process (ie. analyzing request,
selecting method to call by annotations, invoking it, serializing
result) somehow? My idea would be to register something that would
"proxy" it...

Also, the objects are quite big and it is not necessary to get all the
members every single time. I would like to have an optional parameter
like http://server/api/v1/users/ID?fields=name,created that would
serialize (and thus call) only getters of requested fields. Is there a
simple way how to implement it with Jersey?

I could fix both mentioned issues by simply not using Jersey at all and
calling Jackson directly instead, but then I would lose all that nice
annotation processing...

Thanks.

Best regards,
  Martin