在Spring Data JPA中删除相同的事务后插入

时间:2013-09-17 14:54:04

标签: jpa eclipselink spring-data spring-data-jpa

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

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

    @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);
    
  2. 插入新用户的预测并保存主对象(事件)。

    eventRepository.save(event);
    
  3. 当这项服务结束时,提交是由AOP提出的,但只能在第一次尝试时使用...而不是在下一次尝试...

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

    更新

    我尝试了它并且它不起作用(适配器插入我之前删除的对象):

    @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);
    }
    

2 个答案:

答案 0 :(得分:3)

Hibernate改变了命令的顺序。它按以下顺序工作: 以特殊顺序执行所有SQL和二级缓存更新,以便不会违反外键约束:

    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会在删除语句之前执行所有插入操作。 可能的选择是:
1.在删除后显式调用entityManager.flush()。 要么 2.尽可能更新现有行,并从rest创建ToBeDeleted List。这将确保使用新值更新现有记录并保存全新记录。

答案 1 :(得分:1)

PostgreSQL(也许还有其他数据库)可以将约束推迟到提交之前。这意味着它接受事务中的重复项,但是在提交时强制执行唯一约束。

USER
相关问题