Java 使用@ManyToOne和@OneToMany的空列表
我尝试使用双向映射。首先是守则: MapPointJava 使用@ManyToOne和@OneToMany的空列表,java,jakarta-ee,jpa,Java,Jakarta Ee,Jpa,我尝试使用双向映射。首先是守则: MapPoint @Entity public class MapPoint implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private int x; private int y; private String name; @ManyToOne private GameMap map; private static f
@Entity
public class MapPoint implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private int x;
private int y;
private String name;
@ManyToOne
private GameMap map;
private static final long serialVersionUID = 1L;
public MapPoint() {
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getX() {
return this.x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return this.y;
}
public void setY(int y) {
this.y = y;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public GameMap getMap() {
return map;
}
public void setMap(GameMap map) {
this.map = map;
}
游戏地图
@Entity
public class GameMap implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToMany(mappedBy="map")
private List<MapPoint> pois;
private static final long serialVersionUID = 1L;
public GameMap()
{
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public List<MapPoint> getPois() {
return pois;
}
public void setPois(List<MapPoint> pois) {
this.pois = pois;
}
当我尝试使用它时,我的游戏地图上总是有一个空的POI列表。这些表是在部署期间创建的,所有Mappoint都由JPA自己在数据库中设置了MAP_ID,所以应该连接它。我的问题是,我做错了什么?我过去经常使用这个,但这是一个很长的时间和任何其他类似的问题在这里没有帮助我
非常感谢
manytone
默认情况下,关系是延迟加载的,如果您想立即加载它们,则必须指定延迟加载。试试看:@OneToMany(mappedBy="map", fetch=FetchType.EAGER)
private List<MapPoint> pois;
@OneToMany(mappedBy=“map”,fetch=FetchType.EAGER)
私人名单;
或者,如果在持久性上下文中调用
getPois()
,列表中应该填充数据。实际添加到poi列表中的代码在哪里?由于双向关系,你需要处理双方,JPA不会为你这样做。你能再解释一下吗?我现在觉得自己非常愚蠢,因为我以前经常这样做:(如何定义GameMap.findall
呢?@namedquerys(@NamedQuery(name=“GameMap.findall”,query=“SELECT map FROM GameMap map map”))确实有效,但列表中不包含任何元素。其余的都很好:)谢谢!Fetchtype.EAGER帮助了我,尽管我确信我以前从未使用过它,而且它仍然满足了我的需求:)对我也起了作用..但现在findbyid不起作用..为什么:(
@OneToMany(mappedBy="map", fetch=FetchType.EAGER)
private List<MapPoint> pois;