具有双向关联的 Hibernate 删除问题

Hibernate deletion issue with a bidirectional association

我将 Spring Data JPA (1.7.2-RELEASE) 与 Hibernate (4.3.8.Final) 和 MySQL (5.5) 结合使用。我想在双向关联中管理两个实体。实体的保存和更新工作正常,但删除不起作用。

@Entity
public class Beacon extends AbstractEntity {

@OneToMany(fetch = FetchType.EAGER, mappedBy = "beacon", cascade = ALL)
private Set<Comment> comments;

/**
 * @return the comments
 */
public Set<Comment> getComments() {
    return comments;
}

/**
 * @param comments the comments to set
 */
public void setComments(Set<Comment> comments) {
    this.comments = comments;
}
}

@Entity
public class Comment extends AbstractEntity {

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "beacon_id")
private Beacon beacon;

public Beacon getBeacon() {
    return beacon;
}

public void setBeacon(Beacon beacon) {
    this.beacon = beacon;
}
}

有一个带有评论的信标存储在数据库中,我想删除评论但它不起作用。我没有遇到异常,但该实体仍存在于数据库中。

这是我的单元测试:

 @Test
public void deleteWithStrategyCheck() {

    Beacon beacon = this.beaconRepository.save(createBeacon());

    Comment comment = this.commentRepository.save(createEntity());
    comment.setBeacon(beacon);
    comment = this.commentRepository.save(comment);

    this.commentRepository.delete(comment.getId());

    assertThat(this.commentRepository.exists(comment.getId())).isFalse();
    assertThat(this.beaconRepository.exists(beacon.getId())).isTrue();
    assertThat(this.beaconRepository.findOne(beacon.getId()).getComments()).doesNotContain(comment);
}

如果我通过 sql 语句删除评论,它会起作用。

您需要将 orphanRemoval = true 添加到您的 @OneToMany 映射,并从父信标中删除评论。

如果您删除 Comment 而不将其从父集合中删除,您实际上应该得到异常(除非您没有使用 InnoDB 存储引擎,(并且您应该))。

beacon.getComments().remove(comment), 

到时候再做。 (使用 orphanRemoval 你不需要调用 EM.remove(comment)。没有它,你需要从集合中删除评论并调用 EM.remove(comment).