Use EntityManager with JAX-RS and Jackson in a custom deserializer

I have data for a client formed in JSON:

{ "name":"My Name", "company":{ "id":9 } } 

My object is as follows:

 @Entity public class Customer { @Id Integer id; String name; @Reference Company company; /* getters and setters */ } 

I want to deserialize this data using Jackson and get the link for company through EntityManager.getReference(Company.class, id) . Annotations @Reference is a custom annotation that indicates that I want to use my own deserializer and get a link. The goal is to transparently access company information at the JAX-RS service endpoint.

My question is: how do I insert or create an EntityManager during deserialization?

Here is the code:

 @Provider public class ObjectMapperContext implements ContextResolver<ObjectMapper> { private ObjectMapper mapper; public ObjectMapperContext() { super(); mapper = new ObjectMapper(); mapper.registerModule(new CustomModule()); } @Override public ObjectMapper getContext(Class<?> type) { return mapper; } } 

In CustomModule.java :

 public class CustomModule extends SimpleModule { @Override public void setupModule(SetupContext context) { super.setupModule(context); AnnotationIntrospector ai = new CustomAnnotationIntrospector(); context.appendAnnotationIntrospector(ai); } [...] } 

Finally, in CustomAnnotationIntrospector.java :

 public class CustomAnnotationIntrospector extends AnnotationIntrospector { @Override public Object findDeserializer(Annotated am) { Reference reference = am.getAnnotation(Reference.class); if(reference == null){ return null; } return CustomDeserializer.class; } } 
+4
source share

Source: https://habr.com/ru/post/1438041/


All Articles