这些是我的实体;@Entity public class IpAddress{ @Id @Column(nullable = false, updatable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ") @Getter private Long id; @ManyToOne(fetch = FetchType.LAZY) private final Application application; ..... }@Entitypublic class Application{@Column(nullable = false, updatable = false)private final String applicationId;@OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)private List<IpAddress> ipAddresses = new ArrayList<>();}@Entitypublic class MerchantApplication { @Id @Column(nullable = false, updatable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ") @Getter private Long id; @OneToOne private final Merchant merchant; @OneToOne(cascade = CascadeType.ALL) private final Application application; @ManyToOne(fetch = FetchType.LAZY) private final User user;}这是我尝试删除的服务方法:@Transactional public void deleteIpAddressForMerchant(Long merchantId,Long ipAddressId) { Merchant merchant = merchantRepository.getMerchant(merchantId); MerchantApplication merchantApplication = merchant.getMerchantApplication(); if (Objects.isNull(merchantApplication)) throw new ApplicationNotFoundException(); if (merchantApplication.getApplication().getIpAddresses().size() == 1) { throw new IpAddressCannotBeDeleted(); } IpAddress ipAddress = ipAddressRepository.getByIdAndApplication(ipAddressId, merchantApplication.getApplication()); ipAddressRepository.delete(ipAddress); }当我在服务方法中删除此块时,它工作正常;if (merchantApplication.getApplication().getIpAddresses().size() == 1) { throw new IpAddressCannotBeDeleted(); }但是这样不行。你能帮我吗,有什么问题吗?
2 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
如果您获取一个orphanRemoval = true
在@Transactional
方法中具有属性的实体字段,它会在该方法返回时保存该字段以及您所做的更改。
在你的情况下,你取
merchantApplication.getApplication().getIpAddresses()
但是您没有对其进行任何更改,然后将获取的列表按原样保存。
您可以删除获取列表中要删除的元素。
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
您以编程方式在以下代码中抛出异常:
if (merchantApplication.getApplication().getIpAddresses().size() == 1)
{
throw new IpAddressCannotBeDeleted();
}
默认情况下,如果在未处理的方法中发生运行时异常(try...catch),事务将回滚。你的IpAddressCannotBeDeleted班级有延伸RuntimeException吗?如果是这样,请尝试将以下属性添加到您的@Transactional注释中:
@Transactional(noRollbackFor={IpAddressCannotBeDeleted.class, ApplicationNotFoundException.class})
如果在您的方法实现中抛出了这两种类型的异常,则 `noRollbackFor' 属性可防止 Spring 回滚事务。
添加回答
举报
0/150
提交
取消