问题
I am having a problem leveraging JPA 1.0 via OpenJPA implementation. My data model consists of a Trip which has a OneToMany relationship with Leg and a OneToMany relationship with Passenger. Leg and Passenger have an assocation in PassengerLeg. This is mapped as bidirectional OneToMany/ManyToOne. So essentially I have a diamond in my data model. If a trip has 2 legs and 3 passengers, there will be 6 passengerLegs. For various use cases I have needs to go each direction from each entity. Right now, when I attempt to eagerly load everything, the leg field in PassengerLeg will be null and I cannot figure out why. Here is a skimpy representation of my classes:
@Entity
public class Trip {
@OneToMany(mappedBy = "trip", fetch = FetchType.EAGER)
private List<Leg> legs;
@OneToMany(mappedBy = "trip", fetch = FetchType.EAGER)
private List<Passenger> passengers;
}
@Entity
public class Leg {
@ManyToOne
@JoinColumn(name = "TRIP_ID")
private Trip trip;
@OneToMany(mappedBy = "leg", fetch = FetchType.EAGER)
private List<PassengerLeg> passengers;
}
@Entity
public class Passenger {
@ManyToOne
@JoinColumn(name = "TRIP_ID")
private Trip trip;
@OneToMany(mappedBy = "passenger", fetch = FetchType.EAGER)
private List<PassengerLeg> legs;
}
@Entity
public class PassengerLeg {
@ManyToOne
@JoinColumn(name = "LEG_ID")
private Leg leg; //this will be null
@ManyToOne
@JoinColumn(name = "PASSENGER_ID")
private Passenger passenger;
}
I've spent countless hours reading documentation and anything I can find on Google to figure out what might cause this, but I have not had any luck. Anyone have any ideas what would cause this? Let me know if you need any more information about classes/annotations.
回答1:
JPA Never loads many side eagerly since it can be time consuming operation. Default fetch As mentioned in JPA Specs
- One To One --->Fetch Eager
- One To Many ---> Fetch Lazy
- Many to one---> fetch Eager
- Many To Many---> Fetch Lazy
also I will not advice you to go for Eager fetch since it is heavy operation
来源:https://stackoverflow.com/questions/9711148/jpa-not-eagerly-loading-everything