Issue
Background
I have Maven with Hibernate set up to the point where I can
@GET
@Path("/test")
@Transactional
public Response test() {
Query query = entityManager.createNativeQuery("select * from some_table");
List<Object[]> result = query.getResultList();
return Response.ok(result).build();
}
Current result
The result I get right now is
[
[1, "Something", "Something else"],
[2, "Another", "Anotherother"],
...
]
Desired result
This is almost what I want, except I would like each row to be a Json Object with keys that correspond to the column name. I.e.
[
{"id": 1, "name": "Something", "description": "Something else"},
{"id": 2, "name": "Another", "description": "Anotherother"},
...
]
Question
As far as I can tell, the result I get is because I retrieve the result as List<Object[]>
from the .getResultList()
method. Presumably I have to fetch it as a List<Map<String, Object>>
in some way.
Am I on the right track here, or do I need to reconsider the entire approach?
Solution
Data transformation can be done using a ResultTransformer.
List<JsonObject> l = query.unwrap(org.hibernate.Query.class).setResultTransformer(JsonRT.INSTANCE);
class JsonRT implements ResultTransformer {
public static final JsonRT INSTANCE = new JsonRT();
public Object transformTuple(Object[] tuple, String[] aliases) {
final JsonObject o = new JsonObject();
/* populate object with key/value pair */
return o;
}
}
Answered By - Luca Basso Ricci
Answer Checked By - Robin (JavaFixing Admin)