HHH-9107 throw WrongClassException if attempting to load incorrect

subclass from 2lc
This commit is contained in:
Brett Meyer 2014-04-08 11:19:05 -04:00
parent 0118376f8e
commit 8c94c30eb7
2 changed files with 23 additions and 7 deletions

View File

@ -30,6 +30,7 @@ import org.hibernate.LockMode;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TypeMismatchException;
import org.hibernate.WrongClassException;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cache.spi.entry.CacheEntry;
@ -629,7 +630,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
final CacheKey ck = source.generateCacheKey(
event.getEntityId(),
persister.getIdentifierType(),
persister.getEntityName()
persister.getRootEntityName()
);
final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() );
@ -652,7 +653,17 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
}
CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure().destructure( ce, factory );
return convertCacheEntryToEntity( entry, event.getEntityId(), persister, event );
Object entity = convertCacheEntryToEntity( entry, event.getEntityId(), persister, event );
if ( !persister.isInstance( entity ) ) {
throw new WrongClassException(
"loaded object was of wrong class " + entity.getClass(),
event.getEntityId(),
persister.getEntityName()
);
}
return entity;
}
private Object convertCacheEntryToEntity(

View File

@ -26,8 +26,10 @@ package org.hibernate.test.cache.polymorphism;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.hibernate.Session;
import org.hibernate.WrongClassException;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
@ -58,11 +60,14 @@ public class PolymorphicCacheTest extends BaseCoreFunctionalTestCase {
s = openSession();
s.beginTransaction();
// As the first item is supposed to be a CachedItem1, it shouldn't be returned.
// Note that the Session API is not type safe but, when using the EntityManager.find API, you get a ClassCastException
// if calling find returns the object.
Object thisObjectShouldBeNull = s.get( CachedItem2.class, item1.getId() );
assertNull( thisObjectShouldBeNull );
// See HHH-9107
try {
s.get( CachedItem2.class, item1.getId() );
fail( "Expected a WrongClassException to be thrown." );
}
catch (WrongClassException e) {
//expected
}
s.getTransaction().commit();
s.close();