【问题标题】:Transaction commit error when updating using JpaRepository使用 JpaRepository 更新时事务提交错误
【发布时间】:2021-07-24 21:12:59
【问题描述】:

我有使用 jpaRepository 的 deleteNotice 方法。

public Notice deleteNotice(int id) {
    Notice notice = noticeRepository.findByIdAndVisible(id, true)
            .orElseThrow(() -> new EntityNotFoundException(String.valueOf(id)));
    
    notice.setVisible(false);
            
    return noticeRepository.save(notice);   
}

还有一个实体文件。

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Notice {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Size(min=4, max=10, message="Title should have at least 4 characters")
    private String title;
    
    @JsonIgnore
    private boolean visible;
}

当我在控制器中尝试这个 deleteNotice 时,

@DeleteMapping("/notice/{noticeId}")
public ResponseEntity<Object> deleteNotice(@PathVariable int noticeId){
    return ResponseEntity.ok(noticeService.deleteNotice(noticeId));
}

我收到错误“无法提交 JPA 事务;嵌套异常是 javax.persistence.RollbackException:提交事务时出错”。
我可以就这个问题获得一些建议吗?

【问题讨论】:

  • nested exception:这就是说有原因,你没有包括在内。始终发布整个堆栈跟踪。 (另请注意,对于 JPA 存储库特别是,在进行更改后不需要调用 save,因为 JPA 工具可以神奇地做到这一点。对于其他存储库是必需的。)
  • 我不知道是什么导致了问题。但是您可以尝试在 deleteNotice ins 服务方法上添加@Transactional 注释。更好的是,您可以添加整个堆栈跟踪。

标签: java spring spring-boot spring-data-jpa


【解决方案1】:

将@transactional 放在您的服务类上。

当实体管理器检索到的实体处于持久状态并且在您想要提交时进行更改后,该实体仍被另一个程序使用时,可能会出现此错误。 更多info

stackoverflow也有类似问题

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 2015-11-12
    • 1970-01-01
    • 2020-09-18
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多