在Spring Data JPA中删除相同事务后插入 [英] Insert after delete same transaction in Spring Data JPA

查看:809
本文介绍了在Spring Data JPA中删除相同事务后插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring Data JPA,我在同一事务中有了下一个流程(REQUIRES_NEW):

Using Spring Data JPA I have the next flow inside the same transaction (REQUIRES_NEW) :

  1. 使用此Spring Data JPA存储库方法删除一组用户的预测.

  1. Remove a set of user's predictions with this Spring Data JPA repository method.

@Query(value = "DELETE FROM TRespuestaUsuarioPrediccion resp WHERE resp.idEvento.id = :eventId AND resp.idUsuario.id = :userId")
@Modifying
void deleteUserPredictions(@Param("userId") int userId, @Param("eventId") int eventId);

  • 插入新用户的预测并保存主对象(事件).

  • Insert the new user's predictions and save the master object (event).

    eventRepository.save(event);
    

  • 此服务完成后,提交是由AOP进行的,但仅在第一次尝试时才有效...在以后的尝试中不起作用...

    When this service finishes, the commit is made by AOP but only works in first attemp...not in the next ones...

    如何在不重复事件的预测条目并更新内部每个条目的情况下管理这种情况?

    How can I manage this situation without iterating over event's predictions entries and updating each one inside?

    更新

    我尝试过这种方法,但是它不起作用(适配器插入了我之前删除的对象):

    I tried with that and it doesn't work (the adapter inserts the objects I remove before):

    @Transactional(propagation=Propagation.REQUIRES_NEW, rollbackFor=PlayTheGuruException.class)
    private void updateUserPredictions(final TUsuario user, final TEvento event, final SubmitParticipationRequestDTO eventParticipationRequestDTO) 
    {
        eventRepository.deleteUserPredictions(user.getId(), event.getId());
        EventAdapter.predictionParticipationDto2Model(user, event, eventParticipationRequestDTO);
        eventRepository.save(event);
    }
    

    推荐答案

    休眠更改了命令的顺序.它按以下顺序工作: 以特殊顺序执行所有SQL和二级缓存更新,以免违反外键约束:

    Hibernate changed order of the commands. It works in below order : Execute all SQL and second-level cache updates, in a special order so that foreign-key constraints cannot be violated:

        1. Inserts, in the order they were performed
        2. Updates
        3. Deletion of collection elements
        4. Insertion of collection elements
        5. Deletes, in the order they were performed 
    

    确实是这样.刷新时,Hibernate在delete语句之前执行所有插入操作. 可能的选项是:
    1.删​​除后立即显式调用entityManager.flush(). 或者 2.尽可能更新现有行,然后从其余位置创建ToBeDeleted List.这样可以确保使用新值更新现有记录,并保存全新的记录.

    And that is exactly the case. When flushing, Hibernate executes all inserts before delete statements. The possible option are :
    1. To call entityManager.flush() explicitly just after the delete. OR 2. Wherever possible update existing rows and from rest create ToBeDeleted List. This will ensure that existing records are updated with new values and completely new records are saved.

    这篇关于在Spring Data JPA中删除相同事务后插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆