there are two entity classes:
@Entity
public class Place implements Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
@OneToMany(mappedBy = "place")
private List<Event> events = new ArrayList<Event>();
private String name;
//getters setters
}
@Entity
public class Event implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id;
@OneToMany(mappedBy = "event" , cascade={CascadeType.PERSIST})
private List<Participant> participants = new ArrayList<Participant>();
@ManyToOne(optional=false,fetch=FetchType.EAGER) private Place place;
private String name;
// getters setters
}
the generated tables:
mysql> desc EVENT;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| ID | bigint(20) | NO | PRI | NULL | auto_increment |
| NAME | varchar(255) | YES | | NULL | |
| PLACE_ID | bigint(20) | YES | MUL | NULL | |
+----------+--------------+------+-----+---------+----------------+
mysql> desc PLACE;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| ID | bigint(20) | NO | PRI | NULL | auto_increment |
| LOCATION | varchar(255) | YES | | NULL | |
| NAME | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
Now, I'll code some Java so the Place and Event tables looks in this way:
+----+--------+
| ID | NAME |
+----+--------+
| 1 | Prague |
+----+--------+
+----+-------------+----------+
| ID | NAME | PLACE_ID |
+----+-------------+----------+
| 1 | Programming | 1 |
+----+-------------+----------+
Now, I would like to pick a place and view all its events:
// there's an ejb talking with persistence layer Place p = ejb.getPlaceWithId(1);
and I would think that there's something more than empty collection in p.events, but there is not - based on my observations. Why?
My observations are that the
eventsareLAZYin the code you’re showing:So how did you come to the conclusion that they are empty when loading a given
Placeexactly? Did you try to callsize()on the collection to force the loading (or to iterate on collection items)?Regardless of the answer to the above question, my suggestions would be to
Maybe actually use a
fetch joinif you want to load theeventseagerly: