【发布时间】: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,因此删除不应该影响它们。我也试过直接在数据库中删除它,它没有任何错误,所以这应该意味着关系没问题,对吧?
请帮忙!
【问题讨论】: