问题描述
我有一个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会导致此错误?
1楼
那是因为您加载了一个实体,所以它由Hibernate进行管理。因此,在打开Session时发生的任何更改都会被拦截,并在 Hibernate Session
时传播到数据库。
我怀疑您将一个新的孩子添加到已经包含该孩子实体的一对多集合中。