【问题标题】:Spring's Stored Procedure, parsing the result MapSpring的存储过程,解析结果Map
【发布时间】:2012-01-16 09:46:49
【问题描述】:

我在 MySQL 上安装了 Spring & Hibernate。 我有一个我想调用的 MySQL 存储过程。 该过程采用 2 个浮点参数,并返回一个包含 3 个字段的结果集。整数、整数、浮点数。

我创建了一个扩展 spring 的 StoredProcedure 的类。 这是执行函数:

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);

问题是我不知道如何解析地图结果。 在调试的时候,我看到所有的结果集都在里面,但是它的排列方式很奇怪,我不知道如何提取字段。

我能做的最好的就是向你展示它的外观,就是给你 out (Map) 的 toString() 这里是:

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

【问题讨论】:

    标签: java hibernate spring stored-procedures map


    【解决方案1】:

    我会在调试器中查看类型是什么; IntelliJ 可以很容易地告诉我这一点。

    对我来说,它看起来像 Map<String, Object>。键是“#result-set-1”和“#update-count-1”。

    第一个键的值是一个 Map 列表,每行返回一个 Map。键是列名,值是返回值。

    第二个键的值是一个整数;它为零,因为您执行了 SELECT。

    所以,为了清楚起见,这里是提取结果的方法(抱歉最初的编码错误):

    // Foo is some unknown object that encapsulates each row.
    List<Foo> results = new ArrayList<Foo>();
    Map<String, Object> rows = (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;
    

    【讨论】:

    • 它不编译,其实我不太明白你在for语句中做了什么,这是什么? “地图行:out.get...”
    • 抱歉,那个时间太有雾了。我认为这是正确的。这个想法是从结果 Map 中获取行列表并迭代其 Maps 集合。话是对的;代码错误。
    • 六年前我回答这个问题时并没有错。我在 IDE 和调试器中运行代码!如果 API 发生了变化,那不是我的错。去检查 Jon Skeet 的旧答案,并告诉他什么时候错了。
    【解决方案2】:

    由于您使用的是 Spring,因此您可以使用 Jackson ObjectMapper。 这比第一个答案更简单。

    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>>() {});
    

    即使这个问题已经开放很长时间了,我也希望能有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多