Well, I figured out the cause of the problem, but I'm sure how to fix it. The root of the problem lies in caching.
Code:
@Cacheable (modelId="myCacheModel")
public Tag getTag(String tagName){
Object ret = sessionFactory.getCurrentSession().load(Tag.class, tagName);
return (Tag)ret;
}
The above function caches the tag object (I'm using ehcache) that is being used to populate the loaded page (via getWritingsByTag function). So here is what I think is happening:
-The user loads page 1 for the tag "someTagName".
-getTag(someTagName) is called which fetches the tag from the database, loads it, caches it, and returns it as someTagObject.
-getWritingsByTag(0, 10, someTagObject)
-The page is populated with the results of the getWritingsByTag() and everything works fine.
-The user loads page 2 for the tag "someTagName".
-The collection someTagObject.getTaggedByThis() goes out of scope (something to do with the way hibernate handles persistent collections by wrapping them in a PersistentCollection object)
-getTag(someTagName) is called which gets intercepted and redirected to cache which returns someTagObject
-getWritingsByTag(10, 10, someTagObject) is called
-Query query = sessionFactory.getCurrentSession().createFilter(tag.getTaggedByThis(), "order by votes desc"); creates an exception because tag.getTaggedByThis() is unreferenced.
I'm still not sure why all of the above is happening the way it is. It seems like hibernate would be smart enough to try to load the collection from the database if it ever becomes "unreferenced". The entire problem goes away if I disable caching on the getTag() function. This is obviously undesirable because it would incur a performance hit.
Has anyone else run into this problem?