【问题标题】:Delete and DeleteById methods don't work in HibernateDelete 和 DeleteById 方法在 Hibernate 中不起作用
【发布时间】:2019-01-23 20:36:25
【问题描述】:

我在 JPARepository 中的 Delete() 和 DeleteById() 方法不起作用,我不知道为什么。 我有 3 个课程:Station、Line 和 StationLine。 StationLine 只是一个绑定前两个的类,并具有一些我稍后在代码中使用的附加属性。

线有属性:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "line", cascade = CascadeType.ALL)
private List<StationLine> stations;

站有属性:

@OneToMany(fetch = FetchType.LAZY, mappedBy="station", cascade=CascadeType.ALL)
private List<StationLine> stationLines;

StationLine 有属性:

@ManyToOne(optional=false)
private Station station;

@ManyToOne(optional=false)
private Line line;

问题出在代码的下一部分:

for(StationLine sl : stationsToRemove) {
    StationLine found = stationLineRepository.findById(sl.getId()).orElse(null);
    if(found == null) { throw new StationNotFoundException("Station " + sl.getStation().getName() + " not found!"); }

    stationLineRepository.deleteById(found.getId());

    found = stationLineRepository.findById(found.getId()).orElse(null);
    if(found != null) {throw new StationNotFoundException("Station " + found.getId() + " " + found.getStation().getName() + " should be null but it is not!");} 
}

如您所见,我在 DeleteById() 之前和之后添加了一些代码,这不是必需的,只是为了检查是否一切正常。在删除之前它总是会找到 StationLine 对象,这是可以的,但在它也找到它之后,如果之前删除它就不好了。

Delete() 的情况相同。

如果我是正确的,在这些关系中,Station 和 Line 应该完全独立于 StationLine,因此删除不应该影响它们。我也试过直接在数据库中删除它,它没有任何错误,所以这应该意味着关系没问题,对吧?

请帮忙!

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    我不知道您是如何配置 Hibernate 的,但我敢打赌您没有正确处理会话。 如果您不刷新会话,则该对象可能仍在内存中等待提交命令,并且在它发生之前不会更改。

    【讨论】:

    • 嗯可能是。你能告诉我该怎么做吗? :)
    • 您可能需要查看此链接上的答案,以更好地了解会话是什么以及如何做到这一点:link
    • 是的,我想通了:)
    猜你喜欢
    • 1970-01-01
    • 2015-02-08
    • 2021-05-13
    • 2017-03-10
    • 1970-01-01
    • 2017-07-17
    • 2016-06-12
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多