M
M
maxvinogradov2021-09-08 18:32:53
Java
maxvinogradov, 2021-09-08 18:32:53

How to delete an Entity and all associated Entities along with it?

Here is an example of Entity, extra methods and fields are omitted.

public class Restaurant extends AbstractNamedEntity {
    @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Vote> votes;
    @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Dish> dishes;
}

If I delete Restaurant now, then a lot of SQL happens because each Entity is deleted by a separate SQL.
Those. if there is 200 Dish, then there will be 202 SQL.

How can I remove this without spamming SQL queries? I read an article that CascadeType.Remove cannot be used with ToMany associations.

NamedGraph not working, catching ConstraintViolationException
public static final String GRAPH_RESTAURANT_WITH_VOTES_DISHES = "Restaurant with votes-dishes.Graph";
    @Transactional
    @Modifying
    @EntityGraph(GRAPH_RESTAURANT_WITH_VOTES_DISHES)
    @Query("DELETE FROM Restaurant r WHERE r.id=:id")
    int deleteRestaurantById(int id);


Is there a way to do this in one @Query?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question