Handling data return types with Mybatis SQL Builder

1.3k Views Asked by At

I am relatively new to Java MyBatis. I came across SQL Builder class in MyBatis. However, I don't understand how to handle the result of the SELECT SQL query, especially if the columns are going to be different in each case while using SQL Builder. Is there an example which can help me understand how to write this?

Usually, I use Mapper XML files with ResultMap to retrieve the output of an SQL statement.

1

There are 1 best solutions below

0
On

I figured out the way to get it to work. I am not sure if it is the correct way.

In the XML I made the following entry

<select id="readSignals" resultType="map">
  ${query}
</select>

The ${query} is passed from a QueryBuilder class and the resultType is set to "map". This cause myBatis to return a List> where each Map in the list is a row. The String contains the column name and Object contains the data.

I use the following code to convert the List> into JSON.

public static JSONObject convertToJSON(List<Map<String, Object>> queryData) {
  JSONObject queryJSONOutput = new JSONObject();
  JSONArray outputArray = new JSONArray();
  queryData.stream().forEach(d -> {
    JSONObject jsonObject = new JSONObject();
    for (String key: d.keySet()) {
      jsonObject.put(key, d.get(key));
    }
    outputArray.put(jsonObject);
  });
  queryJSONOutput.put("data", outputArray);
  return queryJSONOutput;
}