简体   繁体   中英

Hibernate: how to delete entities in many-to-many relationships with extra attributes

I have the following relationships:

@OneToMany(fetch = FetchType.EAGER, mappedBy="note", cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Review> reviews = new HashSet<>();

in Note.java and

@OneToMany(fetch = FetchType.EAGER, mappedBy = "expert", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Review> notes = new HashSet<>();

in Expert.java .

As you can see, they refer to the Review class, which represents a M to N relationship between Note and Expert. As I needed to add extra attributes to this relationship, I have created a ReviewId class and a Review class as follows:

@Embeddable
public class ReviewId implements Serializable {

    @Column(name = "fk_note")
    protected Long noteId;

    @Column(name = "fk_expert")
    protected Long expertId;

    [...]
}

@Entity
public class Review {
    @EmbeddedId
    private ReviewId id;

    private int value;

    private String comment;

    @ManyToOne
    @JoinColumn(name = "fk_note", insertable = false, updatable = false)
    private Note note;

    @ManyToOne
    @JoinColumn(name = "fk_expert", insertable = false, updatable = false)
    private Expert expert;

    [...]
}

When I try to delete a Note or an Expert that appear in this relationship, I get the following error:

Cannot delete or update a parent row: a foreign key constraint fails (`db_example`.`review`, CONSTRAINT `FKls65s9wl28v98ts2kifir37p7` FOREIGN KEY (`fk_note`) REFERENCES `note` (`id`))

How can I make Hibernate delete all Reviews related to a certain Note/Expert when I delete them? Thanks!

This can be done with FluentJPA :

long noteId; //passed as a parameter

FluentQuery query = FluentJPA.SQL((Review review) -> {

    DELETE().FROM(review);
    WHERE(review.getId().getNoteId() == noteId);
});

...
query.createQuery(em).executeUpdate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM