Home > other >  SpringBoot CrudRepository trying to update instead of create new entity
SpringBoot CrudRepository trying to update instead of create new entity

Time:07-30

Spring Boot save method is trying to update and returns error like:

org.springframework.dao.IncorrectUpdateSemanticsDataAccessException: Failed to update entity [com.xx.xx.Account@78a31407]. Id enter image description here

And here is the code:

@RequestMapping(path = "/banking/add", method = RequestMethod.POST)
public @ResponseBody ResponseEntity addAccount(@Validated @RequestBody Account account) throws IOException {
    if(!account.getType().equals("TL")  && !account.getType().equals("Altın")  && !account.getType().equals("Dolar")) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Account Type: "   account.getType());
    }

    System.out.println(account.getId());
    account.setLastDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
    BankingLogger.writeAccountToTheFile(account);

    AccountCreateSuccessResponse res = new AccountCreateSuccessResponse("Account Created", account.getId());
    this.repository.save(account);
    return ResponseEntity.status(HttpStatus.CREATED).body(res);
}

and here is the request json:

{
        "id": "1",
        "name" : "Doğukan",
        "surname" : "Gülyaşar",
        "email" : "[email protected]",
        "tc" : "123123123",
        "type" : "Dolar",
        "isDeleted": "false"
}

CodePudding user response:

Remove the id from the payload. Create or update logic is triggered by having or not having id. If the id is set beforehand, the entity with specified id is updated, otherwise new entity is created and id will be assigned by the database.

  • Related