Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DTO in Play Framework

I have a situation in my Play Framework application where a bunch of models depend on other models, which creates potential dangers when trying to serialize them to JSON. Also, there are a few properties in every model, which I do not want to expose to the client. Last, but not least, some of the properties in the moel instance which the web client receives are not really coming from the DB, but from a third-party web service.

I heard that it is possible to apply a custom serializer before rendering the object to JSON, but I would like to use an even simpler approach: DTO which is then serialized to JSON.

The question is, where I should I place the DTO conversion function for every Model class? Controller? Model? Maybe the best approach would be to follow the serializer strategy and create a few conversion classes - one for each Model?

My biggest fear is that the convertors should know about each other as well, because obviously I would like to turn each of the Book instances in an Author instance to DTO first, and then turn the Author in a DTO as well. Is this really bad?

like image 754
Preslav Rachev Avatar asked Mar 17 '12 22:03

Preslav Rachev


2 Answers

In a standard Java EE app (Spring), you should use the Dozer framework to make conversion between model objects and DTOs.

In the Play! context, I should place the DTO and converters in a dedicated package, or in a subpackage of models.

like image 92
ndeverge Avatar answered Nov 15 '22 00:11

ndeverge


I'm using the model class as DTO and using the @NoJsonExpose annotation for properties or other model dependencies that I do not want to expose.

Here is the implementation of @NoJsonExpose annotation and the improved RenderJson result object that considers it.

https://play.lighthouseapp.com/projects/57987/tickets/1605-propose-nojsonexpose-annotation-to-make-renderjsoners-life-better

Just need to override the Controller's renderJson() to use the new RenderJson object.

like image 28
Don Grem Avatar answered Nov 15 '22 02:11

Don Grem