Question

I'm using QueryDSL in a project already and was wondering if I could (ab)use it to make my POJO-to-JSON conversion type-safe. Currently I do something like this:

converter.toJson(entity, entity.getDetail(), "detail");

and I thought it would be cool if I could change it to this:

QEntity q = QEntity.entity;
converter.toJson(entity, q.detail);

and then, in the toJson method use the q.detail argument to extract the name of the property as well as call the getter on the entity to retrieve the value. It should be doable using EntityPathBase.getType().getSimpleClassName() and using reflection for the getter, but I'm wondering if that's something QueryDSL can do already.

Outcome I went with using Path.getMetadata().getName() which is available on query entities and returns the property name in the given sample. Combined with a BeanMap to retrieve the property values (as suggested by Timo, thanks!). And now I don't have to keep a getter call in sync with a string. Granted it's a tradeoff as reflection is now used, sacrificing some performance for better maintainability.

Was it helpful?

Solution

You could do something like that using the Querydsl Collections GuavaHelpers class http://www.querydsl.com/static/querydsl/3.2.4/apidocs/com/mysema/query/collections/GuavaHelpers.html

Although I am not sure if the typesafety is needed in this case, since your target model (JSON) is not statically typed.

I'd probably just use a Bean helper class such as BeanMap for this case, if your use case is to copy bean properties to a JSON structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top