Chimaera
Chimaera

Reputation: 5

Empty List using @ManyToOne and @OneToMany

I try to use a bidrectional Mapping. First the Code: 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 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;
}

GameMap

@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;
}

Bean

Query q = em.createNamedQuery("GameMap.findall");
return (GameMap) q.getResultList().get(0);

When I try to use it, my GameMap always has a emptry List of POIS. The Tables are created during Deployment and all Mappoint have MAP_ID set in Database by JPA itself, so it should be connected. My Question is, what am I doing wrong? I used this a lot in the past, but its a long time and any other similar Question here is not helping me.

Thanks a Lot!

Upvotes: 0

Views: 584

Answers (1)

fonkap
fonkap

Reputation: 2509

ManyToOne relationships are Lazy loaded by default, if you want to eager load them you must specify that. Try:

@OneToMany(mappedBy="map", fetch=FetchType.EAGER)
private List<MapPoint> pois;

Or if you call getPois() inside persistence context, the list should be populated with data.

Upvotes: 1

Related Questions