我有一个 Play 项目,我在其中使用以下带有 spring @Transactional 注释的方法:
@Autowired
Home home;
@Transactional
public Result update() {
try {
JsonNode jsonNode = request().body().asJson();
User user = home.updateFromJsonString(jsonNode.toString());
return ok("Updated successfully.");
} catch (Exception e){
return badRequest("Error updating");
}
}
updateFromJsonString 方法位于另一个项目中,它使用 hibernate 更改 sql 表。问题是,当 @Transactional 注释丢失时,这个“更新”方法可以正常工作,但是当它存在时,我会得到以下异常:
[error] o.h.e.j.s.SqlExceptionHelper - Duplicate entry '1-10' for key 'PRIMARY'
[error] play - Cannot invoke the action, eventually got an error: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.
exception.ConstraintViolationException: could not execute statement
知道问题是什么,以及为什么 @Transactional 会出现此错误吗?
最佳答案
那是因为您加载了一个实体,因此它由 Hibernate 管理,因此, session 打开时发生的任何更改都会被 dirty checking mechanism 拦截。并在 flushing 上传播到数据库Hibernate session
。
我怀疑您将一个新子实体添加到已包含该子实体的一对多集合中。
关于java - Spring @Transactional 在 Hibernate 中产生问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726255/