OptimisticLockingFailureException:批处理更新返回了意外的行数

时间:2019-05-28 22:27:54

标签: java jpa spring-data

我的Spring Web MVC应用程序中有一个简单的“父子”单向单向关系。我有2个RESTful API:POST和PUT。

父实体:

@Entity
@EqualsAndHashCode(exclude = {"children", "id"})
public class Parent {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "PARENT_ID", nullable = false, updatable = false)
    private Set<Child> children = new HashSet<>();
}

子实体:

@Entity
@EqualsAndHashCode(exclude = {"id"})
public class Child {

    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String name;
}

控制器:

@RestController
@RequestMapping("/parent")
public class Controller {

    @Autowired
    private ServiceImpl serviceImpl;

    @PostMapping
    public ResponseEntity<Parent> post(@RequestBody final Parent parent) {
        return new ResponseEntity<Parent>(serviceImpl.create(parent), HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<Parent> put(@RequestBody final Parent parent) {
        return new ResponseEntity<Parent>(serviceImpl.update(parent), HttpStatus.OK);
    }
}

服务层:

@Service
public class ServiceImpl implements inter {
    @Autowired
    ParentRepository repository;

    public Parent create(Parent parent) {
        return repository.save(parent);
    }

    @Transactional(readOnly = true)
    public Parent findById(Long id) {
        return repository.findById(id).orElseThrow(IllegalArgumentException::new);
    }

    @Transactional
    public Parent update(Parent toUpdate) {
        Parent retrieved = this.findById(toUpdate.getId());

        retrieved.getChildren().retainAll(toUpdate.getChildren());
        retrieved.getChildren().addAll(toUpdate.getChildren());

        return repository.save(retrieved);
    }
}

我有一个父级存储库。 我作为POST api的一部分一起创建了父级和子级

我需要通过PUT更新“父母和孩子”。 但是,当我尝试替换已创建的父项的一个或多个子项时,出现错误:

{"timestamp":"2019-05-27T20:21:53.451+0000","status":500,"error":"Internal Server Error","message":"Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1","path":"/parent"}

仅当执行具有多个线程的简单JMETER性能测试时,才会出现此问题。

如果我在关系的父级将CascadeType更改为MERGE,则更新有效,但是新实体的持久性将通过Post api失败。

0 个答案:

没有答案