Spring Boot CrudRepository执行更新而非新增实体问题排查
问题
Spring Boot调用save方法时触发了更新操作,返回错误:
org.springframework.dao.IncorrectUpdateSemanticsDataAccessException: Failed to update entity [com.xx.xx.Account@78a31407]. Id 1 not found in database.
但数据库是空的,实际想要新增新的实体。
接口代码
@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); }
请求JSON
{ "id": "1", "name" : "Doğukan", "surname" : "Gülyaşar", "email" : "xxxx@gmail.com", "tc" : "123123123", "type" : "Dolar", "isDeleted": "false" }
解决方案
核心原因:Spring Data JPA的save()方法逻辑是实体ID不为空时执行更新,ID为空时执行新增。你在请求里主动传入了id:1,JPA误认为这是已存在的实体,尝试更新但数据库无对应记录,因此报错。
解决方法:
- 优先方案:移除请求中的
id字段:如果ID是自增或自动生成的,不要手动传入。同时确保Account实体的ID字段配置了自动生成策略,示例:@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - 若需手动指定ID:先调用
repository.existsById(id)检查数据库是否存在该ID的记录,不存在再执行save();或者使用repository.saveAndFlush(),但存在性校验更稳妥。
内容的提问来源于stack exchange,提问作者DGulyasar
相关产品推荐
相关产品推荐

