众所周知 jpa 做复杂查询是比较麻烦的,现在有一个业务场场景
公司项目都是微服务架构 所以业务数据库也是分开 ,现在有一个需求 商品价格 针对不同用户指定折扣但是 商品数据库 和 用户信息的数据库是分开的没法用关联查询。
而项目的持久层用的是 jpa ,分页相关功能已经封装好了。
引用包 org.springframework.data.domain.Page
Page<Map<String, Object>> result = service.find(new PageAdapter<>(new ViewPage<>(param.getPage(), param.getPageSize())), param);
List<Map<String, Object>> content = result.getContent();
if (CollectionUtils.isNotEmpty(content)) {
for (Map<String, Object> price : content) {
price.put("customerName", "张三");
}
}
发现的问题
1、 当page 中对象为map是无法编辑的
如果向上面这样去编辑会抛出异常:
java.lang.UnsupportedOperationException: A TupleBackedMap cannot be modified.
这种数据要编辑只能转变成别的数据类型后去修改(尝试new 一个新的page对象也是无法编辑里面的数据,希望知道原因的朋友下面留言告知谢谢)
解决方法:这里采用的方法是通过 对象转json 然后去替换对应的数据块(RestResponse 是封装返回的数据结构类)
修改后的代码:
public RestResponse list(PriceParam param) {
try {
Page<Map<String, Object>> result = service.find(new PageAdapter<>(new ViewPage<>(param.getPage(), param.getPageSize())), param);
List<Map<String, Object>> content = result.getContent();
List<Map<String, Object>> content1 = new ArrayList<Map<String,Object>>();
if (CollectionUtils.isNotEmpty(content)) {
for (Map<String, Object> price : content) {
// '0:全局;1:客户 2:客户类型',
String type = (String) price.get("type");
if ("2".equals(type)) {
Map<String, Object> map1 =new HashMap<String, Object>(price);
map1.put("customerName", "张三");
content1.add(map1);
}
}
}
JSONObject result1 = JSON.parseObject(JSON.toJSONString(result));
result1.put("content", content1);
return RestResponse.createSuccessRes(result1);
} catch (Exception e) {
log.error(e.getMessage(), e);
return RestResponse.createFailRes("失败:" + e);
}
}
2、 当page 中对象为自定义的类时,可以编辑自定义的类中的数据
public RestResponse list(PriceParam entity) {
try {
Page<PriceParam> list = service.list(entity);
for (PriceParam priceParam : list) {
priceParam.setCustomerName("张三");
}
return RestResponse.getSuccessResponse(list);
} catch (Exception e) {
log.error("============="+this.getClass(),e);
return RestResponse.getFailResponse(e);
}
}
这种直接编辑是可以修改其中的数据的。
tip:展示代码有删减,照搬会报错