如何在 Controller 的 java spring JPA 中进行批量更新

Posted

技术标签:

【中文标题】如何在 Controller 的 java spring JPA 中进行批量更新【英文标题】:how to do bulk updates in java spring JPA at Controller 【发布时间】:2020-03-15 15:52:39 【问题描述】:

以下是我只更改一个数据的方法

    @RequestMapping(value = "/updateroomstatus", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<SaveResponse> updateRoomStatus(@RequestBody Request<RoomDetail> request, HttpServletRequest httpServletRequest) throws ParseException, JsonProcessingException 
    Response<SaveResponse> rvalue = new Response<>();
    Status status = new Status();
    String user = request.getSession().getUserId();
    log.info("Headers : " + HttpUtil.getHeadersInfo(httpServletRequest).toString());
    log.info("Incoming request from " + httpServletRequest.getRemoteAddr() + ":" + httpServletRequest.getRemotePort() + "\n"
            + "    Method    : " + httpServletRequest.getMethod() + "\n"
            + "    TLS       : " + httpServletRequest.isSecure() + "\n"
            + "    Path      : " + httpServletRequest.getRequestURI() + "\n"
            + "    Body      : " + mapper.writeValueAsString(request));
    RoomDetail updatedData = request.getPayload();

    Optional<RoomDetail> getData = roomDetailRepository.findById(updatedData.getId());
    if(getData.isPresent()) 
        RoomDetail oldData = getData.get();
        //just one data can update
        oldData.setStatus(updatedData.getStatus());
        oldData.setDescription(updatedData.getDescription());

        roomDetailRepository.saveAndFlush(oldData);
        status.setStatusCode("000");
        status.setStatusDesc("Success");
     else 
        status.setStatusCode("001");
        status.setStatusDesc("Data Not Found");
    

    log.info("Resp : " + status.toString());
    rvalue.setStatus(status);
    return rvalue;

使用 Postman 发出请求时,会是这样。这很好用

        
        "id": 91,
        "description": "normal",
        "status": "Occupied"
        

我想要做的是批量更新,这会改变很多数据。它看起来像这样

     [
        
        "id": 91,
        "description": "Very Good",
        "status": "Occupied"
        ,
        
        "id": 93,
        "description": "Normal",
        "status": "Vacant Dirty"
        ,

        
        "id": 98,
        "description": "Not bad",
        "status": "Occupie Dirty"   
        
    ]

我得到的信息是通过添加数组和循环进行批量更新。谁能帮忙?

【问题讨论】:

请查看***.com/questions/50772230/… 【参考方案1】:

更改可以接受 RoomDetails 列表的请求正文。迭代它,相同的代码应该可以工作

    @RequestMapping(value = "/updateroomstatus", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public Response<List<SaveResponse>> updateRoomStatus(@RequestBody List<RoomDetail> roomDetails)

   List<SaveResponse> responses = new ArrayList<>();
   for(RoomDetail roomDetail : roomDetails)
        Optional<RoomDetail> getData = roomDetailRepository.findById(roomDetail.getId());
        if(getData.isPresent()) 
            RoomDetail oldData = getData.get();
            //just one data can update
            oldData.setStatus(updatedData.getStatus());
            oldData.setDescription(updatedData.getDescription());

            roomDetailRepository.saveAndFlush(oldData);
            status.setStatusCode("000");
            status.setStatusDesc("Success");
         else 
            status.setStatusCode("001");
            status.setStatusDesc("Data Not Found");
        

        log.info("Resp : " + status.toString());
        rvalue.setStatus(status);
        responses.add(rvalue);
     
return responses;

【讨论】:

完成...方括号可能是额外的/更少的。请保重【参考方案2】:

我要求你做的是创建一个 BulkRoomDetail 类,并在该类中包含一个 RoomDetail 的列表字段,例如名为“rooms”。之后,将您的 Request&lt;RoomDetail&gt; 替换为 Request&lt;BulkRoomDetail&gt;。改变它,你将不得不这样请求:


    "rooms": [
        
        "id": 91,
        "description": "Very Good",
        "status": "Occupied"
        ,
        
        "id": 93,
        "description": "Normal",
        "status": "Vacant Dirty"
        ,

        
        "id": 98,
        "description": "Not bad",
        "status": "Occupie Dirty"   
        
    ]

您的代码将接近此:

    @RequestMapping(value = "/updateroomstatus", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<SaveResponse> updateRoomStatus(@RequestBody Request<BulkRoomDetail> request,
            HttpServletRequest httpServletRequest) throws ParseException, JsonProcessingException 
        Response<SaveResponse> rvalue = new Response<>();
        Status status = new Status();
        String user = request.getSession().getUserId();
        log.info("Headers : " + HttpUtil.getHeadersInfo(httpServletRequest).toString());
        log.info("Incoming request from " + httpServletRequest.getRemoteAddr() + ":"
                + httpServletRequest.getRemotePort() + "\n" + "    Method    : " + httpServletRequest.getMethod() + "\n"
                + "    TLS       : " + httpServletRequest.isSecure() + "\n" + "    Path      : "
                + httpServletRequest.getRequestURI() + "\n" + "    Body      : " + mapper.writeValueAsString(request));

        BulkRoomDetail bulkOfRooms = request.getPayload();
        List<RoomDetail> rooms = bulkOfRooms.getRooms();

        BulkRoomDetail newUpdatedBulkResponse = new BulkRoomDetail();

        rooms.forEach(room -> newUpdatedBulkResponse.getRooms().add(updateRoom(room)));

        rvalue.setBulk(newUpdatedBulkResponse); // dont know what rvalue is :/
        return rvalue;
    

    private RoomDetail updateRoom(RoomDetail room) 
        Optional<RoomDetail> getData = roomDetailRepository.findById(room.getId());
        if (getData.isPresent()) 
            RoomDetail oldData = getData.get();
            // just one data can update
            oldData.setStatus(room.getStatus());
            oldData.setDescription(room.getDescription());

            return roomDetailRepository.saveAndFlush(oldData);
        

        room.setStatus("001");
        room.setDescription("Data Not Found");
        return room;
    


** 没测试好吗?!? :)

【讨论】:

好的,先生,感谢您的意见,但抱歉不行 :) @RikoIkoJanuar 对此感到抱歉:(。但如果你想要一个可以复制和过去的 100% 功能代码,我认为你不会找到。上面的代码是什么的想法你必须基于数组和循环来做。好看

以上是关于如何在 Controller 的 java spring JPA 中进行批量更新的主要内容,如果未能解决你的问题,请参考以下文章

基于maven+ssm的增删改查之测试相关ssm环境是否成功

Angular-Sprout:module.controller() 函数未定义;无法添加控制器

如何在 Controller 的 java spring JPA 中进行批量更新

spring的@ControllerAdvice注解

java程序员培训:为什么要用Spring含三大框架简介

SpringBoot helloworld