简体   繁体   中英

Spring @Transactional makes problems in Hibernate

I have a Play project in which I am using the following method with a spring @Transactional annotation:

@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. 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:

[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?

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 .

I suspect you add a new child to a one-to-many collection which already contains that child entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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