提取特定列表后,Spring Jpa删除操作不起作用

时间:2018-09-20 13:00:44

标签: java spring hibernate spring-boot jpa

这些是我的实体;

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

     .....
 }

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

@Entity
public 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 个答案:

答案 0 :(得分:1)

如果您在orphanRemoval = true方法中获取具有@Transactional属性的实体字段,则该方法返回时,它将保存该字段及其更改。

在您的情况下,您可以获取

merchantApplication.getApplication().getIpAddresses()

但是您对此没有任何更改,然后将提取的列表按原样保存。

您可以在获取的列表中删除要删除的元素。

答案 1 :(得分:0)

您以编程方式在以下代码中引发异常:

 if (merchantApplication.getApplication().getIpAddresses().size() == 1) 
 {
     throw new IpAddressCannotBeDeleted();
 }
如果在未处理的方法内发生运行时异常,则默认回滚

事务(try ... catch)。您的IpAddressCannotBeDeleted类是否扩展了RuntimeException?如果是这样,请尝试将以下属性添加到您的@Transactional批注中:

 @Transactional(noRollbackFor={IpAddressCannotBeDeleted.class, ApplicationNotFoundException.class})

如果在方法实现中抛出了这两种类型的异常,则`noRollbackFor'属性可防止Spring回滚事务。