use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.
the class CollectionLoadContext method addCollectionToCache.
/**
* Add the collection to the second-level cache
*
* @param lce The entry representing the collection to add
* @param persister The persister
*/
private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
final SessionFactoryImplementor factory = session.getFactory();
final boolean debugEnabled = LOG.isDebugEnabled();
if (debugEnabled) {
LOG.debugf("Caching collection: %s", MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session));
}
if (!session.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(session)) {
// some filters affecting the collection are enabled on the session, so do not do the put into the cache.
if (debugEnabled) {
LOG.debug("Refusing to add to cache due to enabled filters");
}
// EARLY EXIT!!!!!
return;
}
final Object version;
if (persister.isVersioned()) {
Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(lce.getKey(), persister);
if (collectionOwner == null) {
// resolution against the PC anyway just to be safe since the lookup should not be costly.
if (lce.getCollection() != null) {
final Object linkedOwner = lce.getCollection().getOwner();
if (linkedOwner != null) {
final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier(linkedOwner, session);
collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(ownerKey, persister);
}
}
if (collectionOwner == null) {
throw new HibernateException("Unable to resolve owner of loading collection [" + MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session) + "] for second level caching");
}
}
version = getLoadContext().getPersistenceContext().getEntry(collectionOwner).getVersion();
} else {
version = null;
}
final CollectionCacheEntry entry = new CollectionCacheEntry(lce.getCollection(), persister);
final CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
final Object cacheKey = cache.generateCacheKey(lce.getKey(), persister, session.getFactory(), session.getTenantIdentifier());
boolean isPutFromLoad = true;
if (persister.getElementType().isAssociationType()) {
for (Serializable id : entry.getState()) {
EntityPersister entityPersister = ((QueryableCollection) persister).getElementPersister();
if (session.getPersistenceContext().wasInsertedDuringTransaction(entityPersister, id)) {
isPutFromLoad = false;
break;
}
}
}
// CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
if (isPutFromLoad) {
try {
session.getEventListenerManager().cachePutStart();
final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode() != CacheMode.REFRESH);
if (put && factory.getStatistics().isStatisticsEnabled()) {
factory.getStatistics().secondLevelCachePut(persister.getCacheAccessStrategy().getRegion().getName());
}
} finally {
session.getEventListenerManager().cachePutEnd();
}
}
}
use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.
the class DefaultInitializeCollectionEventListener method initializeCollectionFromCache.
/**
* Try to initialize a collection from the cache
*
* @param id The id of the collection of initialize
* @param persister The collection persister
* @param collection The collection to initialize
* @param source The originating session
*
* @return true if we were able to initialize the collection from the cache;
* false otherwise.
*/
private boolean initializeCollectionFromCache(Serializable id, CollectionPersister persister, PersistentCollection collection, SessionImplementor source) {
if (!source.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(source)) {
LOG.trace("Disregarding cached version (if any) of collection due to enabled filters");
return false;
}
final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled();
if (!useCache) {
return false;
}
final SessionFactoryImplementor factory = source.getFactory();
final CollectionRegionAccessStrategy cacheAccessStrategy = persister.getCacheAccessStrategy();
final Object ck = cacheAccessStrategy.generateCacheKey(id, persister, factory, source.getTenantIdentifier());
final Object ce = CacheHelper.fromSharedCache(source, ck, persister.getCacheAccessStrategy());
if (factory.getStatistics().isStatisticsEnabled()) {
if (ce == null) {
factory.getStatisticsImplementor().secondLevelCacheMiss(cacheAccessStrategy.getRegion().getName());
} else {
factory.getStatisticsImplementor().secondLevelCacheHit(cacheAccessStrategy.getRegion().getName());
}
}
if (ce == null) {
return false;
}
CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure().destructure(ce, factory);
final PersistenceContext persistenceContext = source.getPersistenceContext();
cacheEntry.assemble(collection, persister, persistenceContext.getCollectionOwner(id, persister));
persistenceContext.getCollectionEntry(collection).postInitialize(collection);
// addInitializedCollection(collection, persister, id);
return true;
}
use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.
the class DefaultLoadEventListener method assembleCacheEntry.
private Object assembleCacheEntry(final StandardCacheEntryImpl entry, final Serializable id, final EntityPersister persister, final LoadEvent event) throws HibernateException {
final Object optionalObject = event.getInstanceToLoad();
final EventSource session = event.getSession();
final SessionFactoryImplementor factory = session.getFactory();
if (traceEnabled) {
LOG.tracev("Assembling entity from second-level cache: {0}", MessageHelper.infoString(persister, id, factory));
}
EntityPersister subclassPersister = factory.getEntityPersister(entry.getSubclass());
Object result = optionalObject == null ? session.instantiate(subclassPersister, id) : optionalObject;
// make it circular-reference safe
final EntityKey entityKey = session.generateEntityKey(id, subclassPersister);
TwoPhaseLoad.addUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.NONE, entry.getVersion(), session);
Type[] types = subclassPersister.getPropertyTypes();
Object[] values = entry.assemble(result, id, subclassPersister, session.getInterceptor(), session);
// intializes result by side-effect
TypeHelper.deepCopy(values, types, subclassPersister.getPropertyUpdateability(), values, session);
Object version = Versioning.getVersion(values, subclassPersister);
LOG.tracev("Cached Version: {0}", version);
final PersistenceContext persistenceContext = session.getPersistenceContext();
boolean isReadOnly = session.isDefaultReadOnly();
if (persister.isMutable()) {
Object proxy = persistenceContext.getProxy(entityKey);
if (proxy != null) {
// there is already a proxy for this impl
// only set the status to read-only if the proxy is read-only
isReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
}
} else {
isReadOnly = true;
}
persistenceContext.addEntry(result, (isReadOnly ? Status.READ_ONLY : Status.MANAGED), values, null, id, version, LockMode.NONE, true, subclassPersister, false);
subclassPersister.afterInitialize(result, session);
persistenceContext.initializeNonLazyCollections();
// upgrade the lock if necessary:
//lock(result, lockMode);
//PostLoad is needed for EJB3
//TODO: reuse the PostLoadEvent...
PostLoadEvent postLoadEvent = event.getPostLoadEvent().setEntity(result).setId(id).setPersister(persister);
for (PostLoadEventListener listener : postLoadEventListeners(session)) {
listener.onPostLoad(postLoadEvent);
}
return result;
}
use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.
the class DefaultResolveNaturalIdEventListener method loadFromDatasource.
/**
* Performs the process of loading an entity from the configured
* underlying datasource.
*
* @param event The load event
*
* @return The object loaded from the datasource, or null if not found.
*/
protected Serializable loadFromDatasource(final ResolveNaturalIdEvent event) {
final SessionFactoryImplementor factory = event.getSession().getFactory();
final boolean stats = factory.getStatistics().isStatisticsEnabled();
long startTime = 0;
if (stats) {
startTime = System.nanoTime();
}
final Serializable pk = event.getEntityPersister().loadEntityIdByNaturalId(event.getOrderedNaturalIdValues(), event.getLockOptions(), event.getSession());
if (stats) {
final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy = event.getEntityPersister().getNaturalIdCacheAccessStrategy();
final String regionName = naturalIdCacheAccessStrategy == null ? null : naturalIdCacheAccessStrategy.getRegion().getName();
final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
factory.getStatisticsImplementor().naturalIdQueryExecuted(regionName, milliseconds);
}
//PK can be null if the entity doesn't exist
if (pk != null) {
event.getSession().getPersistenceContext().getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(event.getEntityPersister(), pk, event.getOrderedNaturalIdValues());
}
return pk;
}
use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.
the class InLogicOperatorNode method initialize.
@Override
public void initialize() throws SemanticException {
final Node lhs = getLeftHandOperand();
if (lhs == null) {
throw new SemanticException("left-hand operand of in operator was null");
}
final Node inList = getInList();
if (inList == null) {
throw new SemanticException("right-hand operand of in operator was null");
}
// one-or-more params.
if (SqlNode.class.isAssignableFrom(lhs.getClass())) {
Type lhsType = ((SqlNode) lhs).getDataType();
AST inListChild = inList.getFirstChild();
while (inListChild != null) {
if (ExpectedTypeAwareNode.class.isAssignableFrom(inListChild.getClass())) {
((ExpectedTypeAwareNode) inListChild).setExpectedType(lhsType);
}
// fix for HHH-9605
if (CollectionFunction.class.isInstance(inListChild) && ExpectedTypeAwareNode.class.isInstance(lhs)) {
final Type rhsType = ((CollectionFunction) inListChild).getDataType();
((ExpectedTypeAwareNode) lhs).setExpectedType(rhsType);
}
inListChild = inListChild.getNextSibling();
}
}
final SessionFactoryImplementor sessionFactory = getSessionFactoryHelper().getFactory();
if (sessionFactory.getDialect().supportsRowValueConstructorSyntaxInInList()) {
return;
}
final Type lhsType = extractDataType(lhs);
if (lhsType == null) {
return;
}
final int lhsColumnSpan = lhsType.getColumnSpan(sessionFactory);
final Node rhsNode = (Node) inList.getFirstChild();
if (!isNodeAcceptable(rhsNode)) {
return;
}
int rhsColumnSpan;
if (rhsNode == null) {
// early exit for empty IN list
return;
} else if (rhsNode.getType() == HqlTokenTypes.VECTOR_EXPR) {
rhsColumnSpan = rhsNode.getNumberOfChildren();
} else {
final Type rhsType = extractDataType(rhsNode);
if (rhsType == null) {
return;
}
rhsColumnSpan = rhsType.getColumnSpan(sessionFactory);
}
if (lhsColumnSpan > 1 && rhsColumnSpan > 1) {
mutateRowValueConstructorSyntaxInInListSyntax(lhsColumnSpan, rhsColumnSpan);
}
}
Aggregations