簡體   English   中英

如何決定何時更新,刪除和插入

[英]How to decide when to update, delete and insert

我正在使用spring data jpa創建服務。 我必須在一個保存按鈕上進行插入,更新和刪除操作。 為了保存和更新,我在代碼中使用存儲庫保存方法。 為了決定是否需要更新或插入,我正在檢查記錄數。

如果我發送一條記錄,那么我就能夠成功進行保存和更新操作。

但是我的問題是,當我發送兩個已經存在的記錄時,需要更新的數據庫。 但是在我的情況下,我正在檢查記錄計數,因此它用於保存而不是更新。

誰能告訴我什么條件需要檢查更多,然后才能進行更新? 或者告訴我另一種方式來決定何時進行更新,何時進行插入以及何時進行刪除?

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);

傑森輸入

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

只需使用CrudRepository.existsById(ID id)

該文件說:

返回具有給定id的實體是否存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM