Currently, 2-nd level collection caching system is STUPID.
Let's look into this method of the class PersistentList:
Code:
public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner)
throws HibernateException {
Serializable[] array = ( Serializable[] ) disassembled;
int size = array.length;
beforeInitialize( persister, size );
for ( int i = 0; i < size; i++ ) {
list.add( persister.getElementType().assemble( array[i], getSession(), owner ) );
}
}
This is a very BAD idea.
Let me explain. First of all, collection caches contain only object IDs, not the objects themselves.
That means collections and their elements are cached separately. And it's definitely possible, that most of collection elements will be pushed out of the cache.
And in this case Type.assemble(...) will issue "select * from blah where blah.id=?" FOR EACH COLLECTION ELEMENT NOT IN THE 2nd-level CACHE. Of course, it's SLOW.
The possible solution will be something like (pseudocode):
Code:
public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner)
throws HibernateException {
Object[] ids = ( Object[] ) disassembled;
int size = ids.length;
beforeInitialize( persister, size );
List res=getSession().createCriteria(
persister.getElementType().getEntityName()).
.add(Restriction.in("id",ids)
.list();
//Add loading in chunks, etc.
list.addAll(res);
}
Is there any pitfall I can't see?