Вопрос

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