stdcall
stdcall

Reputation: 28900

Spring's Stored Procedure, parsing the result Map

I've got a setup with Spring & Hibernate over MySQL. I have a MySQL Stored-Procedure I would like to call. The procedure takes 2 float arguments, and returns a result-set with 3 fields. Integer,Integer,Float.

I created a class which extends spring's StoredProcedure. This is the execute function:

public Map execute(float longitude, float latiude) {
Map inparams = new HashMap(2);
inparams.put("longitude", (float) longitude);
inparams.put("latitude", (float) latiude);
Map out = execute(inparams);

The problem is that I don't know how to parse the map result. When I'm debugging, I see that all the result-set is in there, but It arranged in a strange way, and I don't know how to extract the fields.

The best I can do to show you how it looks, is to give you the toString() of out (Map) Here it is:

{#result-set-1=[{id=4, out1=100, distance=40.9}, {id=5, out1=100, distance=47.7}, {id=6, out1=100, distance=22.3}, {id=7, out1=100, distance=27.4}, {id=8, out1=100, distance=22.1}, {id=9, out1=100, distance=18.3}, {id=10, out1=100, distance=20.1}, {id=11, out1=100, distance=28.6}, {id=12, out1=100, distance=23.1}], #update-count-1=0}

Upvotes: 1

Views: 5804

Answers (2)

duffymo
duffymo

Reputation: 308988

I'd look in a debugger to see what the types are; IntelliJ could tell me this easily.

It looks like a Map<String, Object> to me. The keys are "#result-set-1" and "#update-count-1".

The value for the first key is a List of Maps, one Map per row returned. The keys are the column names and the values are the returned values.

The value for the second key is an Integer; it's zero because you did a SELECT.

So, in the interest of spelling it out, here's how to extract your results (sorry for the initial coding error):

// Foo is some unknown object that encapsulates each row.
List<Foo> results = new ArrayList<Foo>();
List<Map<String, Object>> rows = (List<Map<String, Object>>) 
out.get("#result-set-1");
for (Map row : rows) {
    int id = row.get("id");
    int out1 = row.get("out1");
    double distance = row.get("distance");
    results.add(new Foo(id, out1, distance));
}
return results;

Upvotes: 4

Guigreg
Guigreg

Reputation: 513

Since you are using Spring you can use the Jackson ObjectMapper. It's more simple than the first answer.

class Foo {
  private int id;
  private int out1;
  private double distance;
  // getters and setters
}
ObjectMapper objectMapper = new ObjectMapper();
List<Foo> list = objectMapper.convertValue(execute.get("#result-set-1"), new TypeReference<List<Foo>>() {});

I hope that helps even if this question is open for a long time :)

Upvotes: 0

Related Questions