【问题标题】:Hibernate deletion issue with a bidirectional association双向关联的休眠删除问题
【发布时间】:2015-05-31 20:00:15
【问题描述】:

我将 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;
}
}

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

这是我的单元测试:

 @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 语句删除评论,它会起作用。

【问题讨论】:

  • 怎么知道实体还在数据库中?测试是事务性的吗?最后会回滚吗?
  • 我正在使用 mysql shell 来检查数据库中的实体

标签: mysql spring hibernate jpa spring-data-jpa


【解决方案1】:

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

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

beacon.getComments().remove(comment), 

然后会做这项工作。 (使用 orphanRemoval 您不需要调用 EM.remove(comment)。没有它,您需要从集合中删除评论并调用 EM.remove(comment)。

【讨论】:

  • 如果 OP 会检查休眠详细日志,他会找到 delete from comment where id = ? was aborted.,因为当 em 自动刷新时,他发现评论仍在培根的评论集合中。
猜你喜欢
  • 2013-02-15
  • 1970-01-01
  • 2019-07-31
  • 2011-02-16
  • 2012-05-23
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多