문제

I'm working with JPA 2 + Hibernate 4 and I'm implementing some CRUD operations on model entities.

Now I need to prevent a certain entity (EntityB) to be deleted when a related entity (EntityA) exists in database:

@Entity
public class EntityA {
    @Id
    private int id;

    @OneToOne(mappedBy = "entityA", optional = false, fetch = FetchType.LAZY)
    private EntityB entityB;

    //...
}

@Entity
public class EntityB {
    @Id
    private int id;

    @OneToOne
    @JoinColumn(name = "id")
    private EntityA entityA;

    //...
}

Is there any way to achieve this using relationship options or should I check EntityA existence in my dao/repository before removing EntityB?

NOTE I need this also for @ManyToOne relationships.

도움이 되었습니까?

해결책

If you want to prevent that in your code, than simply do not delete that entity (by checking that manually). There is no possibility to do that with annotations.

On the other side, this sounds to me rather like a need for a DB constraint. If those entities are already related, then simply add a foreign key constraint (if none is existent). If not, than think of adding one.

PS: if you already have a relationship, check the CascadeType.REMOVE setting.

다른 팁

I don't think you can solve this with annotations. You should manally check related-entity existence before.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top