我在路线和站点之间有一对多的关系。为了维护审核跟踪,我的Stop实体有一个“历史”布尔值。
获取路线时,我想忽略历史停靠点,因此我构造了此查询:
@Query("select r from Route r " +
"left join fetch r.schedules schedule " +
"left join fetch r.stops stop " +
"where r.routeId = :routeId and stop.historic = false ")
Optional<Route> findByIdLoadStops(@Param("routeId") int routeId);
当路线具有非历史停靠点且没有停靠点时,此方法工作正常,但是当路线仅具有历史停靠点(这不应该发生,但我希望至少能够处理它)时,它将返回一个空可选,就好像执行内部联接一样。
记录由休眠创建的JPA查询时,我可以看到该查询使用左外部联接。
我做错了什么?
路由和停止实体:
@Table(name = "route")
@Entity
public class Route {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "routeId", columnDefinition = "SMALLINT(5) UNSIGNED")
private int routeId;
@Column(name = "locked")
private boolean locked = false;
@OneToMany(mappedBy = "route",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
@OrderBy("stopTime asc")
private SortedSet<Stop> stops = new TreeSet<>();
public Route() {
}
}
@Table(name = "stop", uniqueConstraints = {
@UniqueConstraint(columnNames = {"stopTime", "routeId"}),
@UniqueConstraint(columnNames = {"stopName", "routeId"})})
@Entity
public class Stop implements Comparable<Stop> {
@Id
@Column(name = "stopId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int stopId;
@Column(name = "routeId",
columnDefinition = "SMALLINT(5)",
updatable = false, insertable = false)
private int routeId;
@ManyToOne(cascade = CascadeType.MERGE,
fetch = FetchType.LAZY)
@JoinColumn(name = "routeId")
private Route route;
@Column(name = "stopTime")
private LocalTime stopTime;
@Column(name = "stopName")
private String stopName;
@JoinColumn(name = "originalId", referencedColumnName = "stopId")
@ManyToOne(fetch = FetchType.LAZY)
private Stop originalStop = this;
@Column(name = "historic")
private boolean historic = false;
public Stop() {
}
}