users@jersey.java.net

Setting Id Field on JPA Entities

From: Jay Bloodworth <johnabloodworth3_at_gmail.com>
Date: Sun, 26 Sep 2010 08:47:54 -0400

 This is arguably more a JPA question than a Jersey question, but I'm
doing the stuff in a RESTful context and the way Jersey marshals objects
may be relevant, so here I am.

I want to do something like:

@PUT
@Consumes("application/json")
@Produces("text/html")
public String doUpdate(Entity entity) {
    em.merge(entity);
    return "Success";
}

And then update the datastore by PUTing something like {"id" : 5, "name"
: "New Name", etc}.

(This is actually only my test case; the real handler will return a
Response and will use a Path Param to set the id. But the issue is the
same either way.)

The problem is that JPA (I'm using Eclipselink) blocks explicit setting
of the @Id field, so it ends up being null in the entity passed to the
handler. I've looked at the bookmarks example and it sidesteps this
issue by using a proxy object to receive the updated fields, then copies
them into a managed copy of the entity from the datastore. That's easy
enough to do, but it seems to undermine some of the elegance and even
purpose of the ORM if you have to copy the fields around yourself.

Any suggestions?

Thanks,
Jay