3

I am working on a project using JPA (EclipseLink 2.5.2) and Jersey 2.27 running on Tomcat 8 under Java 8. Currently I retrieve results using mapped entities and also some simple lists (distinct values, key-value pairs). I have implemented server-side paging, filtering and sorting. Now I'm trying to add the ability to dynamically aggregate data sets.

I've searched on SO and other sites for the best way to serialize a list of Tuples returned from my criteria builder query. So far I haven't found anything that answers my question. I can think of three ways to do it barring some good pointers from here:

  1. Use reflection to create the appropriate object and supply it in my query
  2. Run through the results one at a time and write out my own JSON for each element to a StringBuffer
  3. ArrayList<HashMap<String, Object>> where the HashMap is built using the alias and matching result then added to the list, list is serialized as normal

So if there is no "easy" way to serialize a list of tuples, which method above makes the most sense? Option 3 definitely works, but feels like a kludge to me.

John Kuhns
  • 506
  • 4
  • 20
  • 2
    `List>` looks pretty normal. Maybe you can convert result to list of maps on `EclipseLink` level? See this question: [JPA 2.0 native query results as map](https://stackoverflow.com/questions/7595328/jpa-2-0-native-query-results-as-map). I am not sure but maybe there is a way to convert `List` to `List` as well? – Michał Ziober Mar 07 '19 at 21:40
  • 1
    @MichałZiober thanks! I rewrote some of my code to use CreateQuery instead of CreateTupleQuery and to use your suggestion, it makes the code much cleaner and also allows me to remove all the manipulation of the results. I appreciate the help! – John Kuhns Mar 07 '19 at 23:26
  • If you think my comment is helpful and helped you I can convert it to an answer so you can accept it. Maybe it will be useful for others. – Michał Ziober Mar 07 '19 at 23:31
  • @MichałZiober I can't imagine a better answer, so please do. – John Kuhns Mar 07 '19 at 23:33

1 Answers1

2

Generally using Reflection in business logic does not sound good so you should eliminate first option (1.). (2.) - serialising object one by one sounds good when you want to use streaming API, in your case it is not an option. Third one (3.) looks pretty normal and it a good solution because it is generic and List<Map<String, Object>> fits extremely well to JSON specification:

  • JSON array - List
  • JSON object - Map
    • property - String
    • any JSON object - Object

You should try to convert query result on EclipseLink level. See JPA 2.0 native query results as map question where is suggested to convert query result to ResultType.Map.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146