use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.
the class Loader method instanceNotYetLoaded.
/**
* The entity instance is not in the session cache
*/
private Object instanceNotYetLoaded(final ResultSet rs, final int i, final Loadable persister, final String rowIdAlias, final EntityKey key, final LockMode lockMode, final EntityKey optionalObjectKey, final Object optionalObject, final List hydratedObjects, final SharedSessionContractImplementor session) throws HibernateException, SQLException {
final String instanceClass = getInstanceClass(rs, i, persister, key.getIdentifier(), session);
// see if the entity defines reference caching, and if so use the cached reference (if one).
if (session.getCacheMode().isGetEnabled() && persister.canUseReferenceCacheEntries()) {
final EntityDataAccess cache = persister.getCacheAccessStrategy();
final Object ck = cache.generateCacheKey(key.getIdentifier(), persister, session.getFactory(), session.getTenantIdentifier());
final Object cachedEntry = CacheHelper.fromSharedCache(session, ck, cache);
if (cachedEntry != null) {
CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure().destructure(cachedEntry, factory);
return ((ReferenceCacheEntryImpl) entry).getReference();
}
}
final Object object;
if (optionalObjectKey != null && key.equals(optionalObjectKey)) {
// its the given optional object
object = optionalObject;
} else {
// instantiate a new instance
object = session.instantiate(instanceClass, key.getIdentifier());
}
// need to hydrate it.
// grab its state from the ResultSet and keep it in the Session
// (but don't yet initialize the object itself)
// note that we acquire LockMode.READ even if it was not requested
LockMode acquiredLockMode = lockMode == LockMode.NONE ? LockMode.READ : lockMode;
loadFromResultSet(rs, i, object, instanceClass, key, rowIdAlias, acquiredLockMode, persister, session);
// materialize associations (and initialize the object) later
hydratedObjects.add(object);
return object;
}
use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.
the class DefaultLoadEventListener method getFromSharedCache.
private Object getFromSharedCache(final LoadEvent event, final EntityPersister persister, SessionImplementor source) {
final EntityDataAccess cache = persister.getCacheAccessStrategy();
final Object ck = cache.generateCacheKey(event.getEntityId(), persister, source.getFactory(), source.getTenantIdentifier());
final Object ce = CacheHelper.fromSharedCache(source, ck, persister.getCacheAccessStrategy());
if (source.getFactory().getStatistics().isStatisticsEnabled()) {
if (ce == null) {
source.getFactory().getStatistics().entityCacheMiss(StatsHelper.INSTANCE.getRootEntityRole(persister), cache.getRegion().getName());
} else {
source.getFactory().getStatistics().entityCacheHit(StatsHelper.INSTANCE.getRootEntityRole(persister), cache.getRegion().getName());
}
}
return ce;
}
use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.
the class DefaultLoadEventListener method lockAndLoad.
/**
* If the class to be loaded has been configured with a cache, then lock
* given id in that cache and then perform the load.
*
* @param event The initiating load request event
* @param persister The persister corresponding to the entity to be loaded
* @param keyToLoad The key of the entity to be loaded
* @param options The defined load options
* @param source The originating session
*
* @return The loaded entity
*
* @throws HibernateException
*/
private Object lockAndLoad(final LoadEvent event, final EntityPersister persister, final EntityKey keyToLoad, final LoadEventListener.LoadType options, final SessionImplementor source) {
SoftLock lock = null;
final Object ck;
final EntityDataAccess cache = persister.getCacheAccessStrategy();
if (persister.canWriteToCache()) {
ck = cache.generateCacheKey(event.getEntityId(), persister, source.getFactory(), source.getTenantIdentifier());
lock = persister.getCacheAccessStrategy().lockItem(source, ck, null);
} else {
ck = null;
}
Object entity;
try {
entity = load(event, persister, keyToLoad, options);
} finally {
if (persister.canWriteToCache()) {
cache.unlockItem(source, ck, lock);
}
}
return event.getSession().getPersistenceContext().proxyFor(persister, keyToLoad, entity);
}
use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.
the class AbstractEntityPersister method initializeLazyProperty.
public Object initializeLazyProperty(String fieldName, Object entity, SharedSessionContractImplementor session) {
final EntityEntry entry = session.getPersistenceContext().getEntry(entity);
final InterceptorImplementor interceptor = ((PersistentAttributeInterceptable) entity).$$_hibernate_getInterceptor();
assert interceptor != null : "Expecting bytecode interceptor to be non-null";
if (hasCollections()) {
final Type type = getPropertyType(fieldName);
if (type.isCollectionType()) {
// we have a condition where a collection attribute is being access via enhancement:
// we can circumvent all the rest and just return the PersistentCollection
final CollectionType collectionType = (CollectionType) type;
final CollectionPersister persister = factory.getMetamodel().collectionPersister(collectionType.getRole());
// Get/create the collection, and make sure it is initialized! This initialized part is
// different from proxy-based scenarios where we have to create the PersistentCollection
// reference "ahead of time" to add as a reference to the proxy. For bytecode solutions
// we are not creating the PersistentCollection ahead of time, but instead we are creating
// it on first request through the enhanced entity.
// see if there is already a collection instance associated with the session
// NOTE : can this ever happen?
final Serializable key = getCollectionKey(persister, entity, entry, session);
PersistentCollection collection = session.getPersistenceContext().getCollection(new CollectionKey(persister, key));
if (collection == null) {
collection = collectionType.instantiate(session, persister, key);
collection.setOwner(entity);
session.getPersistenceContext().addUninitializedCollection(persister, collection, key);
}
// HHH-11161 Initialize, if the collection is not extra lazy
if (!persister.isExtraLazy()) {
session.initializeCollection(collection, false);
}
interceptor.attributeInitialized(fieldName);
if (collectionType.isArrayType()) {
session.getPersistenceContext().addCollectionHolder(collection);
}
// update the "state" of the entity's EntityEntry to over-write UNFETCHED_PROPERTY reference
// for the collection to the just loaded collection
final EntityEntry ownerEntry = session.getPersistenceContext().getEntry(entity);
if (ownerEntry == null) {
// not good
throw new AssertionFailure("Could not locate EntityEntry for the collection owner in the PersistenceContext");
}
ownerEntry.overwriteLoadedStateCollectionValue(fieldName, collection);
// EARLY EXIT!!!
return collection;
}
}
final Serializable id = session.getContextEntityIdentifier(entity);
if (entry == null) {
throw new HibernateException("entity is not associated with the session: " + id);
}
if (LOG.isTraceEnabled()) {
LOG.tracev("Initializing lazy properties of: {0}, field access: {1}", MessageHelper.infoString(this, id, getFactory()), fieldName);
}
if (session.getCacheMode().isGetEnabled() && canReadFromCache() && isLazyPropertiesCacheable()) {
final EntityDataAccess cacheAccess = getCacheAccessStrategy();
final Object cacheKey = cacheAccess.generateCacheKey(id, this, session.getFactory(), session.getTenantIdentifier());
final Object ce = CacheHelper.fromSharedCache(session, cacheKey, cacheAccess);
if (ce != null) {
final CacheEntry cacheEntry = (CacheEntry) getCacheEntryStructure().destructure(ce, factory);
final Object initializedValue = initializeLazyPropertiesFromCache(fieldName, entity, session, entry, cacheEntry);
interceptor.attributeInitialized(fieldName);
// NOTE EARLY EXIT!!!
return initializedValue;
}
}
return initializeLazyPropertiesFromDatastore(fieldName, entity, session, id, entry);
}
use of org.hibernate.cache.spi.access.EntityDataAccess in project hibernate-orm by hibernate.
the class InitFromCacheTest method execute.
@Test
public void execute() {
doInHibernate(this::sessionFactory, s -> {
Document d = (Document) s.createQuery("from Document fetch all properties").uniqueResult();
assertTrue(isPropertyInitialized(d, "text"));
assertTrue(isPropertyInitialized(d, "summary"));
final EntityDataAccess entityDataAccess = persister.getCacheAccessStrategy();
final Object cacheKey = entityDataAccess.generateCacheKey(d.id, persister, sessionFactory(), null);
final Object cachedItem = entityDataAccess.get((SharedSessionContractImplementor) s, cacheKey);
assertNotNull(cachedItem);
assertTyping(StandardCacheEntryImpl.class, cachedItem);
});
sessionFactory().getStatistics().clear();
doInHibernate(this::sessionFactory, s -> {
Document d = (Document) s.createCriteria(Document.class).uniqueResult();
assertFalse(isPropertyInitialized(d, "text"));
assertFalse(isPropertyInitialized(d, "summary"));
assertEquals("Hibernate is....", d.text);
assertTrue(isPropertyInitialized(d, "text"));
assertTrue(isPropertyInitialized(d, "summary"));
});
assertEquals(2, sessionFactory().getStatistics().getPrepareStatementCount());
doInHibernate(this::sessionFactory, s -> {
Document d = s.get(Document.class, documentID);
assertFalse(isPropertyInitialized(d, "text"));
assertFalse(isPropertyInitialized(d, "summary"));
});
}
Aggregations