JPA Not Eagerly Loading Everything

谁说胖子不能爱 提交于 2019-12-06 08:20:47

问题


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

  1. One To One --->Fetch Eager
  2. One To Many ---> Fetch Lazy
  3. Many to one---> fetch Eager
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!