E
E
Eugene2021-04-10 09:57:09
Hibernate
Eugene, 2021-04-10 09:57:09

Spring Data Jpa how to remove an entity without removing another related entity?

I have a Lesson entity:

@OneToMany(mappedBy="lesson", cascade = {
            CascadeType.ALL
    }, fetch = FetchType.LAZY)
    @Getter @Setter
    private List<Client> clients = new ArrayList<>();


And entity:
Client:
@ManyToOne
    @JoinColumn(name="lesson_ID")
    @Getter @Setter
    private Lesson lesson;

If I delete Lesson through the repository (deleteById), then the record of the associated client is also deleted, but I want only Lesson to be deleted, and the LessonId field of the client is simply set to zero. Is it possible to do this with standard tools or do I need to write requests with pens?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-04-10
@coi175

Good afternoon.
You can try the following:

CascadeType.MERGE,
CascadeType.PERSIST

orphanRemovel = false;
If orphanRemoval = true,then if the client has no lessonId, then it will be deleted, since it is an "orphan". And if vice versa is false, then it will not be deleted.
Here is the difference between CascadeType.REMOVE vs orphanRemoval
https://www.baeldung.com/jpa-cascade-remove-vs-orp...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question