JAX-RS + JPA, how to update/merge only a subset of an Entity's fields?

Viewed 867

Suppose I have the following Entity:

@Entity
@XmlRootElement
@XmlAccessorType( XmlAccessType.FIELD)
public class MyEntity {

    @Id
    @GeneratedValue
    private long id;

    private boolean field1;

    private boolean field2;

    private boolean field3;
}

Suppose I have a REST Web Service that allows clients to POST partial or complete updates to a MyEntity resource. Perhaps the method signature looks something like this:

@POST
@Path("{id}")
public Response postMyEntity(@PathParam("id") long id, MyEntity myEntity)

Below is the JSON that a client might use to update only "field2" of MyEntity with id 101:

{
    "id": 101
    "field2": true
}

If JPA knew that only field2 was set during the de-serialization process then I'd love to persist this change with code as simple as:

entityManager.merge(myEntity);

However, this operation updates field1, field2, and field3.

How do people typically ensure that only the fields explicitly specified in the JSON/XML from the REST request are updated in the database? I've read about people using DTOs in their web service (as opposed to the Entities themselves) and manually figuring out what fields need to be set on the corresponding Entity...however, this use case seems so common that I'm surprised it would require a DIY approach.

1 Answers
Related