If you have defined your one-to-many relationship in JPA like so:
@OneToMany(fetch=FetchType.EAGER, mappedBy="schedule", cascade=CascadeType.MERGE)
@OrderBy("stopSequence ASC")
private List<ScheduleStops> scheduleStops = new ArrayList<ScheduleStops>();
Then you do not need to code a join. Just use the
Java relationships. For example:
Integer stopId = scheduleX.getScheduleStops().get(1);
Or
for (ScheduleStops stop : scheduleX.getScheduleStops() ) {
...
}
You don't have to use OrderBy, but I needed an ordered collection of children, so this saved SQL coding a sort clause.
The default behavior for JPA is lazy loading. I was using this code in an app that detaches the ORM objects from the EntityManager, so I made it do an eager fetch instead. If I hadn't, the collection object would have been null after I detached. If I'd remained attached, a stub would have caused the child SELECT to be done on first access. In either case, eager loading causes an SQL join to be created instead of separate SELECTs for parent and children.