我正在尝试确定是否可以从存储库中删除对象。换句话说:如果删除将导致DataIntegrityViolationException与否。
如果无法删除,则这意味着隐藏前端上的“删除”按钮。

例:
我上了A和B类:

@Entity
public class A{
    @Id
    private UUID id;

    @Column
    private String name;

    @ManyToMany
    private Set<B> bs= new HashSet<>();

    //getter, setter, equals,...
}


@Entity
public class B{
    @Id
    private UUID id;

    @Column
    private String name;

    //getter, setter, equals,...
}


现在,如果要删除B对象(在任何A对象集中),我将得到“ DataIntegrityViolationException”。当然,由于该对象被积极地用作键。

我考虑过先检查A,看看是否有任何引用,然后可以安全地删除我的B实例。但是实际上,这可能有点棘手,因为一个以上的类可以使用B类,而其他类稍后会由不熟悉代码的其他人添加。还有这个...

aRepository.findAll(Example.of(new A(null, null, new HashSet<>(Array.asList(b))));


结果仅传送了绝对垃圾(b的> 20+个对象无处使用)。

第二个想法是通过尝试这样的事情:

    @Transactional //always roll back
    public void inUse(B b) throws TransacationException{
        bRepository.delete(composition);
        throw new TransacationException();
    }


然后像这样检查它:

    public Boolean deleteAble(B b){
        try{
            inUse(b);
        } catch (DataIntegrityViolationException e){
            return false; // constraint violation --> in use!
        } catch (TransacationException e){
            return true;
        }
    }


不幸的是,这些方法似乎都不起作用。
您对如何解决此问题有任何想法吗?

最佳答案

也许您可以使您的@ManyToMany关联双向,例如将其添加到您的类B中:

@ManyToMany(mappedBy = "bs")
private Set<A> as = new HashSet<>();


那就只会像:

someB.getAs().isEmpty()

07-26 09:19
查看更多