Marcu Daniel
Marcu Daniel

Reputation: 85

Delete on many to one relation is not persisting

I am trying to delete an entity from a Many to One relationship. It doesn`t throw any error, but it seems that the item is not deleted and I do not know why. These are my classes:

Client Entity:

public class Client extends BaseEntity<Long> {

    private String name;
    private String email;
    private LocalDate dateOfBirth;
    private LocalDate dateOfRegister;

    @OneToMany(mappedBy = "client", cascade = CascadeType.ALL, fetch =
            FetchType.EAGER)
    private Set<Rental> rentals = new HashSet<>();

    ..............
    }

Movie Entity:

public class Movie extends BaseEntity<Long>{

    private String title;
    private int year;
    private int duration;
    private String genre;
    private double imdbRating;
    private String trailerLink;

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL, fetch =
            FetchType.EAGER)
    private Set<Rental> rentals = new HashSet<>();

    ..................
}

Rental (link) entity:


public class Rental implements Serializable {

    @Id
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "movie_id")
    private Movie movie;

    @Id
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "client_id")
    private Client client;

    @Column(name = "dateRented")
    private LocalDate dateRented;

    @Column(name = "dateDue")
    private LocalDate dateDue;

     .............
}

PrimaryKey class:

public class RentalPK implements Serializable {
    private Movie movie;
    private Client client;
}

In the controller, I do the following:

@Override
    public void deleteRental(RentalPK rentalPK) {
        try {
            rentalRepository.deleteById(rentalPK);
        } catch (Exception e) {
            throw e;
        }
    }

Could someone please explain why it is not deleting?

Upvotes: 0

Views: 47

Answers (1)

Marcu Daniel
Marcu Daniel

Reputation: 85

SOLVED! It seems it was because of the CascadeType.ALL in the Movie and Client entities. It seems that the CascadeType.ALL contains also CascadeType.PERSIST which says that the link entity(rental in my case) can be removed only from the parents. So I have fixed the problem by replacing CascadeType.ALL with CascadeType.REMOVE.

EDIT: I do not know if this is the exact explanation but it worked.

Upvotes: 1

Related Questions