Allow JPA association when deserializing JAX-RS JSON Object
I have some issues combining JAX-RS (in JBoss Wildfly container) with JSON payload and JPA evaluations. Follwoing Scenario:
There are two JPA entities
@Entity
class Organization {
@Id
private long id;
private String name;
}
@Entity
class Empolyee {
@Id
private long id;
@Id
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JsonProperty("organization_id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
private Organization organization;
}
Then I have a JAX-RS service to create a new Employee with the following signature:
@POST
@Consumes({ "application/json" })
public Response create(final Employee employee) {
}
The JSON for the new employee sent by the client looks like this:
{
"name" : "Sam Sample",
"organization_id" : 2
}
My problem is that this JSON (obviously) cannot be deserialized into the "Employee" instance as the mapping from "organization_id" to the corresponding JPA object fails.
How can I configure the JAX-RS (or Jackson JSON mapper) to interpret the "orgainization_id" as a JPA entity id?
source to share
With Jackson, you can define a custom deserializer (see this and this ) that retrieves an object Organization
based on a value organization_id
.
Edit : In this example, let's take a look at how to set up JAX-RS with Jackson using a custom deserializer (as opposed to annotations):
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper objectMapper;
public JacksonContextResolver() throws Exception {
this.objectMapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule myModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
myModule.addDeserializer(MyType.class, new MyTypeDeserializer());
objectMapper.registerModule(myModule);
}
public ObjectMapper getContext(Class<?> objectType) {
return objectMapper;
}
}
source to share