我有以下关系:
@OneToMany(fetch = FetchType.EAGER, mappedBy="note", cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<Review> reviews = new HashSet<>();
在 Note.java 和
中@OneToMany(fetch = FetchType.EAGER, mappedBy = "expert", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Review> notes = new HashSet<>();
在 Expert.java 中。
如您所见,它们引用Review类,它表示Note和Expert之间的M对N关系。当我需要为该关系添加额外的属性时,我创建了一个ReviewId类和一个Review类,如下所示:
@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;
[...]
}
当我尝试删除出现在这种关系中的注释或专家时,出现以下错误:
Cannot delete or update a parent row: a foreign key constraint fails (`db_example`.`review`, CONSTRAINT `FKls65s9wl28v98ts2kifir37p7` FOREIGN KEY (`fk_note`) REFERENCES `note` (`id`))
我如何使Hibernate删除与某个注释/专家相关的所有评论?谢谢!
答案 0 :(得分:0)
这可以通过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();