Java Spring boot + Mysql - Return Json (key-value) 当 mysql 查询结果不匹配对应的任何模型时响应到任何数据库 table

Java Spring Boot + Mysql - Return a Json (key-value) response when the mysql query result does not match any model corresponding to any database table

我是 Spring 引导的初学者,需要一些帮助来解决问题。

在 Spring 引导存储库中,我正在从 mysql 数据库中获取数据。

我有两种来自存储库的 return 值。

a) return 值是我用@Entity 标签定义的模型列表,这个模型对应于 mysql 中的一个 table。例如:下面代码中的 ZoneModel。

@Query(value = "select c from ZoneModel c where c.cityId = ?1")
public List<ZoneModel> getZonesInCity(String cityId);

在这种情况下,我的回应是:

[
  {
    "id": "1",
    "cityId": "1",
    "name": "Phoenix Marketcity",
    "type": "Mall",
    "locationLat": "12.9970372",
    "locationLong": "77.6944303"
  }
]

响应是键值对json。

b) return值不直接对应任何模型或任何模型列表。它有额外的列。

@Query(value = "select id, cityId, name, type, locationLat, locationLong," +
        " (6371 * acos (\n" +
        "cos ( radians(?2) )\n" +
        "* cos( radians( locationLat ) )\n" +
        "* cos( radians( locationLong ) - radians(?3) )\n" +
        "+ sin ( radians(?2) )\n" +
        "* sin( radians( locationLat ) )\n" +
        ")) as distanceInKms\n" +
        "from zone where cityId = ?1\n" +
        "group by id\n" +
        "having distanceInKms < 150\n" +
        "order by distanceInKms\n", nativeQuery = true)

public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);

在这种情况下,响应是:

[
  [
    "1",
    "1",
    "Phoenix Marketcity",
    "Mall",
    "12.9970372",
    "77.6944303",
    0.19478083559705964
  ]
]

响应没有与列名对应的键。

即使存储库中的 return 值与任何模型都不完全匹配,我如何 return 以键作为列名的键值对响应?

public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);

您正在尝试将结果映射到 List of Object arrays。所以 spring 做了你告诉它做的并将它映射到一个对象数组列表。

试试这个:

public List<Map<String, Object>> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);