I am using ormlite in my android project. I have two classes
@DatabaseTable(tableName = "usershows")
public class UserShow {
@DatabaseField(id = true)
private Integer showId;
@ForeignCollectionField(eager = false)
private ForeignCollection<Episode> episodes;
...
}
@DatabaseTable(tableName = "episodes")
public class Episode {
@DatabaseField(id = true)
private Integer episodeId;
@DatabaseField(foreign = true)
private UserShow show;
...
}
I am saving my UserShows objects like in example
UserShow show = new UserShow();
userShowDao.create(show);
for (Episode e: eps) {
e.setShow(show);
episodeDao.create(e);
}
UserShow object have a foreign lazy collection episodes, but when I am trying to get all userShows:
shows = userShowsDao().queryForAll();
I am getting all shows objects with collections of episodes. Why this happens? Collection is lazy and I must to get null or something else but no collection of Episode object. How to make this collection really lazy? It may be cool if ORMLite have ability get objects without lazy collections and initialize when it really need. For example as Hibernate.initialize
method.
Thanks!
The lazy collections have been well tested and are in use by many others so although there could be bugs with it, it is more likely that you are being tricked by the lazy collection class.
When each of the UserShow
objects is retrieved from the DAO, the episodes
will not be null but instead will be set with an instance of LazyForeignCollection
. However, no additional queries will be made and there will be no Episode
data contained by the collection. If you then make a call to one of the methods on the collection such as userShow.getEpisodes().iterator()
, then a separate query is made at that time to allow you to iterate through that show's episodes. That's how the lazy collections work.
If you still think that the lazy collections aren't working then please show us how you are determining that the shows have episode data. To see what queries are being done where, you can enable Android logging with ORMLite.
Edit:
It turns out that @Georgy was using the debugger to investigate the collection. The debugger is most likely calling the same iterator()
or toArray()
methods which cause the collection queries to be issued at that instant. So there weren't any episodes in the collection before the debugger asked for them.