简体   繁体   English

Spring @Transactional在Hibernate中造成问题

[英]Spring @Transactional makes problems in Hibernate

I have a Play project in which I am using the following method with a spring @Transactional annotation: 我有一个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");
    }
}

The updateFromJsonString method is located in another project, where it changes a sql table using hibernate. updateFromJsonString方法位于另一个项目中,在此项目中它使用hibernate更改sql表。 The problem is that this 'update' method works fine when the @Transactional annotation is missing, but when it is there I get the following exception: 问题是当缺少@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

Any idea what is the problem, and why the @Transactional could make this error? 任何想法是什么问题,以及为什么@Transactional会导致此错误?

That's because you load an entity, so it becomes managed by Hibernate, For this reason, any changes happening while the Session is open are intercepted by the dirty checking mechanism and propagated to the database upon flushing the Hibernate Session . 那是因为您加载了一个实体,所以它由Hibernate进行管理。因此,在打开Session时发生的任何更改都会被脏检查机制拦截,并在刷新 Hibernate Session时传播到数据库。

I suspect you add a new child to a one-to-many collection which already contains that child entity. 我怀疑您将一个新的孩子添加到已经包含该孩子实体的一对多集合中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM