如何决定何时更新,删除和插入

时间:2018-10-29 15:30:11

标签: java spring-data-jpa

我正在使用spring data jpa创建服务。我必须在一个保存按钮上进行插入,更新和删除操作。为了保存和更新,我在代码中使用存储库保存方法。为了确定是否需要更新或插入,我正在检查记录数。

如果我发送一条记录,那么我就能够成功进行保存和更新操作。

但是我的问题是当我发送两个已经存在的记录时是db 需要更新。但是在我的情况下,我正在检查记录计数,因此它用于保存而不是更新。

有人可以告诉我什么情况需要检查更多,然后才能进行更新吗?要么 告诉我其他什么方法来决定何时进行更新,何时进行插入以及何时进行删除?

RoomInvestigatorMappingService类

public String updatePiDetails(List<PiDetails> roomInvestMapping) {

    List<RoomInvestigatorMapping> currentRecord = new ArrayList<RoomInvestigatorMapping>();
    for (PiDetails inputRecorObj : roomInvestMapping) {
        currentRecord = roomInvestigatorMappingRepo.findByNRoomAllocationId(inputRecorObj.getnRoomAllocationId());
    }
    int currentRecordCount = currentRecord.size();
    int inputRecordCount = roomInvestMapping.size();

    // update existing record
    if (inputRecordCount == currentRecordCount) {
        for (PiDetails inputObject : roomInvestMapping) {
            for (RoomInvestigatorMapping currentRecordObj : currentRecord) {
                currentRecordObj.nInvestigatorId = inputObject.getnInvestigatorId();
                currentRecordObj.nPercentageAssigned = inputObject.getnPercentageAssigned();
                currentRecordObj.nRoomAllocationId = inputObject.getnRoomAllocationId();
                roomInvestigatorMappingRepo.saveAll(currentRecord);
            }
        }
    }

    //insert new record
    if (inputRecordCount > currentRecordCount) {
        for (PiDetails inputObject : roomInvestMapping) {
            RoomInvestigatorMapping investObj = new RoomInvestigatorMapping();
            investObj.nInvestigatorId = inputObject.getnInvestigatorId();
            investObj.nRoomAllocationId = inputObject.getnRoomAllocationId();
            investObj.nPercentageAssigned = inputObject.getnPercentageAssigned();
            roomInvestigatorMappingRepo.save(investObj);
        }
    }
    return "sucessfully";
}

RoomInvestigatorMappingRepository接口

@Query("select roomInvestMapping from RoomInvestigatorMapping as roomInvestMapping where nRoomAllocationId=?1")
List<RoomInvestigatorMapping> findByNRoomAllocationId(Integer nRoomAllocationId);

Json输入

[
  {
    "nInvestigatorId": 911294,
    "nPercentageAssigned": 50,
    "nRoomAllocationId": 1
  },
  {
    "nInvestigatorId": 911294,
    "nPercentageAssigned": 50,
    "nRoomAllocationId": 2
  }
]

1 个答案:

答案 0 :(得分:0)

只需使用CrudRepository.existsById(ID id)

文档说:

  

返回具有给定id的实体是否存在。