-
Notifications
You must be signed in to change notification settings - Fork 3
How ModelPatchService works?
ModelPatchService is a service responsible for patching model objects.
It uses Reflection combined with annotating fields.
If you want to know more see the code :).
How to use it?
- Implementation in v.1.2 has been changed. Currently fields are matched by name, so its required that both field in model and DTO has the same name. For different json property name use:
JsonProperty
. - You need to mark fields both in DTO and ModelEntity with:
@Patchable
Annotation. This should be enough for simple types like: String, Integers etc.
For more complex objects it is required to provide custom method which e.g. based on new code provided in DTO will find connected object (relation between entities). It can be done from both sides. How to specify method? Simply add parameter in annotation:
@Patchable(method = "methodName")
From Model side method must be like setter which means that it returns void
and as argument receives single parameter which type matches parameter of the same name from DTO.
From DTO side method must be like getter which means it does not have any parameters and return type which corresponds to typ of parameter with same name on model site.
You can find example usage of process described above in TopicEntity which has relation with section. In Patch request:
{
"name": "name",
"sectionCode": "90041086"
}
You send new section code. How it looks in SectionModel:
@ManyToOne
@Patchable
private Section section;
And how it looks in DTO:
@NotBlank(message = "Section code is mandatory.")
@JsonProperty("sectionCode")
@Patchable(method = "sectionPatch")
private String section;
//Custom method used for patch request
@JsonIgnore
public Section sectionPatch()
{
final SectionService sectionService = ContextProvider.getBean(SectionService.class);
return sectionService.findByCodeOrThrowError(section, "TopicPatchSection");
}
PS: It's better to add JsonIgnore
otherwise I encountered some problems with Jackson serialization.
Method is invoked while setting Section in model. Based on sectionService it looks for section with given code and returns it if exists of throw errors if not.
It is not possible to inject bean to simple POJO via annotation so ContextProvider was created, its implementation of ApplicationContextAware which stores ApplicationContext from which you can get DI contaier beans.