需求阐述:
上图是前端页面效果,返回给前端搜索框是这种形式: "[{"loc":[31.12345,33.123456],"title":"black","info":"info"}]"
需求分析:可以看出上面一个集合里的数据是以键值对形式出现的,所以我们先定义一个List<>集合,集合里面是Map<>,即形式是这样的:List<Map<>>
controller层:
@PostMapping(value = "/search")
public List<Map<String, Object>> search(@RequestParam String info) { //info是前台搜索框输入的值
//定义返回前台的形式
List<Map<String,Object>> retList = new ArrayList<>();
//从数据库中按照前台搜索框输入的关键字info查询到的信息保存到集合List<MapSecondGrid>中
List<MapSecondGrid> listShows = mapGridService.findSecondGridList1(info);
//因为List<MapSecondGrid>返回值是对象,下面对对象进行遍历
for( int i = 0 ; i < listShows.size() ; i++) {
//声明一个map集合,用来存储集合里面的键值对,比如:"loc":[31.12345,33.123456]
Map<String,Object> map = new HashMap<>();
//定义一个集合用以存储经度(31.12345)和纬度(33.123456),并且返回值类型为Double
List<Double> strings = new ArrayList<>();
//循环取得集合里面所有的对象
MapSecondGrid mapSecondGrid = listShows.get(i);
// List<Double>里添加对象MapSecondGrid的纬度
strings.add(Double.parseDouble(mapSecondGrid.getLat()));
//经度
strings.add(Double.parseDouble(mapSecondGrid.getLng()));
//将string转为list后转为json (此时arry 包含经纬度)
JSONArray arry = JSONArray.fromObject(strings);
//坐标,形成键值对"loc":[31.12345,33.123456]
map.put("loc",arry);
//存储对象包含的所有信息
map.put("info",mapSecondGrid);
//搜索关键字info的值
map.put("title",mapSecondGrid.getGridName());
//添加到 List<Map<String,Object>>
retList.add(map);
}
return retList;
}
service 层:
/**
*
* @param info
* @return 网格二级搜索框根据grid_name进行查询
*/
List<MapSecondGrid> findSecondGridList1(String info);
serviceImpl 层:
@Override
public List<MapSecondGrid> findSecondGridList1(String info) {
//实现模糊查询
info = info.replaceAll("\\s+","%");
String searchInfo = "%"+info+"%";
//返回二级网格列表信息
return this.mapSecondGridRepository.findSecondGridList1(searchInfo);
}
Repository 层(jpa框架)
@Query(value = "SELECT * from map_second_grid where grid_name like ?1", nativeQuery = true) //模糊查询like ?1
List<MapSecondGrid> findSecondGridList1(String info);