JPA 中Page对象中数据无法编辑的解决办法

众所周知 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:展示代码有删减,照搬会报错

 

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值