Martin
Martin

Reputation: 3058

Why does JPA call sql update on delete?

Let´s assume these two entities:

@Entity
public class MyEntity {
    @Id private String id;
    @OneToMany(mappedBy = "myEntity", cascade = ALL) private Set<MyEntityPredecessor> predecessors;
}

@Entity
public class MyEntityPredecessor{
    @Id private String id;
    @ManyToOne(name = "entityID", nullable = false) private MyEntity myEntity;
    @ManyToOne(name = "entityPre", nullable = false) private MyEntity predecessor;
}

When I try to call a delete with Spring Boot Data (JPA) with a MyEntity Instance, it will work some times (I see the select and then the delete statements in correct order), but sometimes it will try to run an update on the second entity trying to set the "entityPre" Field to null (even thoug it is set to nullable=falsE), causing the DB to send an error (null not allowed!! from DB constraint).

Strangely, this will happen at "random" calls to the delete...

I just call "myEntityRepository.getOne(id)", and then myEntityRepository.delete() with the result... There is no data difference in the DB between calls, the data structure has no null values when calling the delete method, so that should not be the reason.

Why is JPA sometimes trying to call updates on the Predecessor Table, and sometimes directly deleting the values? Am I missing something?

Upvotes: 1

Views: 1131

Answers (1)

Selindek
Selindek

Reputation: 3423

Add a similar ManyToOne annotated set to MyEntity which refers to the other non-nullable property, like:

@OneToMany(mappedBy = "predecessor", cascade = ALL) private Set<MyEntityPredecessor> other;

some explanation: The issue doesn't happen randomly, but happen when you try to delete an entity which is linked to one (or more) MyEntityPredecessor via the predecessor property (which is mapped to the entityPre field)

Only the other field (entityID) is mapped back to the MyEntity object, so the deletion-cascade only happens via by that field.

Upvotes: 1

Related Questions