I am trying to map a sql query with joins through intermediate table to an entity with many-to many association:
Code:
@Entity
@Table(name = "ATMBRANCH_LOCATIONS")
public class AtmBranchLocation extends BaseEntity<AtmBranchLocation> {
@ManyToMany(
cascade = { CascadeType.PERSIST, CascadeType.MERGE },
mappedBy = "locations",
targetEntity = SubwayStation.class
)
private Set<SubwayStation> stations;
}
@Entity
@Table(name = "SUBWAY_STATIONS")
public class SubwayStation extends BaseEntity<SubwayStation> {
@ManyToMany(
targetEntity = AtmBranchLocation.class,
cascade = { CascadeType.PERSIST, CascadeType.MERGE },
fetch = FetchType.LAZY
)
@JoinTable(
name = "NEAREST_SUBWAY_STATIONS",
joinColumns = { @JoinColumn(name = "SUBWAY_STATION_ID") },
inverseJoinColumns = { @JoinColumn(name = "LOCATION_ID") }
)
private Set<AtmBranchLocation> locations;
}
final SQLQuery query1 = session.createSQLQuery(
"select {bl.*}, {ss.*} from ATMBRANCH_LOCATIONS bl " +
" left outer join NEAREST_SUBWAY_STATIONS nss on bl.ID = nss.LOCATION_ID " +
" left outer join SUBWAY_STATIONS ss on ss.ID = nss.SUBWAY_STATION_ID");
query1.addEntity("bl", AtmBranchLocation.class);
query1.addJoin("ss", "bl.stations");
query1.list();
Result: org.hibernate.exception.SQLGrammarException: ORA-00904: "SS"."SUBWAY_STATION_ID": invalid identifier (because SUBWAY_STATION_ID belongs to NEAREST_SUBWAY_STATION, not SUBWAY_STATION)
Is it possible to map such an association?