use of org.hibernate.engine.spi.SessionEventListenerManager in project hibernate-orm by hibernate.
the class TwoPhaseLoad method doInitializeEntity.
private static void doInitializeEntity(final Object entity, final EntityEntry entityEntry, final boolean readOnly, final SharedSessionContractImplementor session, final PreLoadEvent preLoadEvent) throws HibernateException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
final EntityPersister persister = entityEntry.getPersister();
final Serializable id = entityEntry.getId();
final Object[] hydratedState = entityEntry.getLoadedState();
final boolean debugEnabled = LOG.isDebugEnabled();
if (debugEnabled) {
LOG.debugf("Resolving associations for %s", MessageHelper.infoString(persister, id, session.getFactory()));
}
final Type[] types = persister.getPropertyTypes();
for (int i = 0; i < hydratedState.length; i++) {
final Object value = hydratedState[i];
if (value == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
// No resolution is necessary, unless the lazy property is a collection.
if (types[i].isCollectionType()) {
// IMPLEMENTATION NOTE: this is a lazy collection property on a bytecode-enhanced entity.
// HHH-10989: We need to resolve the collection so that a CollectionReference is added to StatefulPersistentContext.
// As mentioned above, hydratedState[i] needs to remain LazyPropertyInitializer.UNFETCHED_PROPERTY
// so do not assign the resolved, unitialized PersistentCollection back to hydratedState[i].
types[i].resolve(value, session, entity);
}
} else if (value != PropertyAccessStrategyBackRefImpl.UNKNOWN) {
// we know value != LazyPropertyInitializer.UNFETCHED_PROPERTY
hydratedState[i] = types[i].resolve(value, session, entity);
}
}
//Must occur afterQuery resolving identifiers!
if (session.isEventSource()) {
preLoadEvent.setEntity(entity).setState(hydratedState).setId(id).setPersister(persister);
final EventListenerGroup<PreLoadEventListener> listenerGroup = session.getFactory().getServiceRegistry().getService(EventListenerRegistry.class).getEventListenerGroup(EventType.PRE_LOAD);
for (PreLoadEventListener listener : listenerGroup.listeners()) {
listener.onPreLoad(preLoadEvent);
}
}
persister.setPropertyValues(entity, hydratedState);
final SessionFactoryImplementor factory = session.getFactory();
if (persister.hasCache() && session.getCacheMode().isPutEnabled()) {
if (debugEnabled) {
LOG.debugf("Adding entity to second-level cache: %s", MessageHelper.infoString(persister, id, session.getFactory()));
}
final Object version = Versioning.getVersion(hydratedState, persister);
final CacheEntry entry = persister.buildCacheEntry(entity, hydratedState, version, session);
final EntityRegionAccessStrategy cache = persister.getCacheAccessStrategy();
final Object cacheKey = cache.generateCacheKey(id, persister, factory, session.getTenantIdentifier());
// we need to be careful not to clobber the lock here in the cache so that it can be rolled back if need be
if (session.getPersistenceContext().wasInsertedDuringTransaction(persister, id)) {
cache.update(session, cacheKey, persister.getCacheEntryStructure().structure(entry), version, version);
} else {
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try {
eventListenerManager.cachePutStart();
final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, useMinimalPuts(session, entityEntry));
if (put && factory.getStatistics().isStatisticsEnabled()) {
factory.getStatistics().secondLevelCachePut(cache.getRegion().getName());
}
} finally {
eventListenerManager.cachePutEnd();
}
}
}
if (persister.hasNaturalIdentifier()) {
persistenceContext.getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(persister, id, persistenceContext.getNaturalIdHelper().extractNaturalIdValues(hydratedState, persister));
}
boolean isReallyReadOnly = readOnly;
if (!persister.isMutable()) {
isReallyReadOnly = true;
} else {
final Object proxy = persistenceContext.getProxy(entityEntry.getEntityKey());
if (proxy != null) {
// there is already a proxy for this impl
// only set the status to read-only if the proxy is read-only
isReallyReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
}
}
if (isReallyReadOnly) {
//no need to take a snapshot - this is a
//performance optimization, but not really
//important, except for entities with huge
//mutable property values
persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
} else {
//take a snapshot
TypeHelper.deepCopy(hydratedState, persister.getPropertyTypes(), persister.getPropertyUpdateability(), //afterQuery setting values to object
hydratedState, session);
persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
}
persister.afterInitialize(entity, session);
if (debugEnabled) {
LOG.debugf("Done materializing entity %s", MessageHelper.infoString(persister, id, session.getFactory()));
}
if (factory.getStatistics().isStatisticsEnabled()) {
factory.getStatistics().loadEntity(persister.getEntityName());
}
}
use of org.hibernate.engine.spi.SessionEventListenerManager in project hibernate-orm by hibernate.
the class MultipleHiLoPerTableGenerator method generate.
public synchronized Serializable generate(final SharedSessionContractImplementor session, Object obj) {
DeprecationLogger.DEPRECATION_LOGGER.deprecatedTableGenerator(getClass().getName());
final SqlStatementLogger statementLogger = session.getFactory().getServiceRegistry().getService(JdbcServices.class).getSqlStatementLogger();
final SessionEventListenerManager statsCollector = session.getEventListenerManager();
final WorkExecutorVisitable<IntegralDataTypeHolder> work = new AbstractReturningWork<IntegralDataTypeHolder>() {
@Override
public IntegralDataTypeHolder execute(Connection connection) throws SQLException {
IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder(returnClass);
int rows;
do {
final PreparedStatement queryPreparedStatement = prepareStatement(connection, query, statementLogger, statsCollector);
try {
final ResultSet rs = executeQuery(queryPreparedStatement, statsCollector);
boolean isInitialized = rs.next();
if (!isInitialized) {
value.initialize(0);
final PreparedStatement insertPreparedStatement = prepareStatement(connection, insert, statementLogger, statsCollector);
try {
value.bind(insertPreparedStatement, 1);
executeUpdate(insertPreparedStatement, statsCollector);
} finally {
insertPreparedStatement.close();
}
} else {
value.initialize(rs, 0);
}
rs.close();
} catch (SQLException sqle) {
LOG.unableToReadOrInitHiValue(sqle);
throw sqle;
} finally {
queryPreparedStatement.close();
}
final PreparedStatement updatePreparedStatement = prepareStatement(connection, update, statementLogger, statsCollector);
try {
value.copy().increment().bind(updatePreparedStatement, 1);
value.bind(updatePreparedStatement, 2);
rows = executeUpdate(updatePreparedStatement, statsCollector);
} catch (SQLException sqle) {
LOG.error(LOG.unableToUpdateHiValue(tableName), sqle);
throw sqle;
} finally {
updatePreparedStatement.close();
}
} while (rows == 0);
return value;
}
};
// maxLo < 1 indicates a hilo generator with no hilo :?
if (maxLo < 1) {
//keep the behavior consistent even for boundary usages
IntegralDataTypeHolder value = null;
while (value == null || value.lt(1)) {
value = session.getTransactionCoordinator().createIsolationDelegate().delegateWork(work, true);
}
return value.makeValue();
}
return hiloOptimizer.generate(new AccessCallback() {
public IntegralDataTypeHolder getNextValue() {
return session.getTransactionCoordinator().createIsolationDelegate().delegateWork(work, true);
}
@Override
public String getTenantIdentifier() {
return session.getTenantIdentifier();
}
});
}
use of org.hibernate.engine.spi.SessionEventListenerManager in project hibernate-orm by hibernate.
the class TableGenerator method generate.
@Override
public Serializable generate(final SharedSessionContractImplementor session, final Object obj) {
final SqlStatementLogger statementLogger = session.getFactory().getServiceRegistry().getService(JdbcServices.class).getSqlStatementLogger();
final SessionEventListenerManager statsCollector = session.getEventListenerManager();
return optimizer.generate(new AccessCallback() {
@Override
public IntegralDataTypeHolder getNextValue() {
return session.getTransactionCoordinator().createIsolationDelegate().delegateWork(new AbstractReturningWork<IntegralDataTypeHolder>() {
@Override
public IntegralDataTypeHolder execute(Connection connection) throws SQLException {
final IntegralDataTypeHolder value = makeValue();
int rows;
do {
final PreparedStatement selectPS = prepareStatement(connection, selectQuery, statementLogger, statsCollector);
try {
selectPS.setString(1, segmentValue);
final ResultSet selectRS = executeQuery(selectPS, statsCollector);
if (!selectRS.next()) {
value.initialize(initialValue);
final PreparedStatement insertPS = prepareStatement(connection, insertQuery, statementLogger, statsCollector);
try {
insertPS.setString(1, segmentValue);
value.bind(insertPS, 2);
executeUpdate(insertPS, statsCollector);
} finally {
insertPS.close();
}
} else {
value.initialize(selectRS, 1);
}
selectRS.close();
} catch (SQLException e) {
LOG.unableToReadOrInitHiValue(e);
throw e;
} finally {
selectPS.close();
}
final PreparedStatement updatePS = prepareStatement(connection, updateQuery, statementLogger, statsCollector);
try {
final IntegralDataTypeHolder updateValue = value.copy();
if (optimizer.applyIncrementSizeToSourceValues()) {
updateValue.add(incrementSize);
} else {
updateValue.increment();
}
updateValue.bind(updatePS, 1);
value.bind(updatePS, 2);
updatePS.setString(3, segmentValue);
rows = executeUpdate(updatePS, statsCollector);
} catch (SQLException e) {
LOG.unableToUpdateQueryHiValue(renderedTableName, e);
throw e;
} finally {
updatePS.close();
}
} while (rows == 0);
accessCount++;
return value;
}
}, true);
}
@Override
public String getTenantIdentifier() {
return session.getTenantIdentifier();
}
});
}
use of org.hibernate.engine.spi.SessionEventListenerManager in project hibernate-orm by hibernate.
the class EntityInsertAction method cacheAfterInsert.
private boolean cacheAfterInsert(EntityRegionAccessStrategy cache, Object ck) {
SharedSessionContractImplementor session = getSession();
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try {
eventListenerManager.cachePutStart();
return cache.afterInsert(session, ck, cacheEntry, version);
} finally {
eventListenerManager.cachePutEnd();
}
}
use of org.hibernate.engine.spi.SessionEventListenerManager in project hibernate-orm by hibernate.
the class EntityUpdateAction method cacheAfterUpdate.
private boolean cacheAfterUpdate(EntityRegionAccessStrategy cache, Object ck) {
final SharedSessionContractImplementor session = getSession();
SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try {
eventListenerManager.cachePutStart();
return cache.afterUpdate(session, ck, cacheEntry, nextVersion, previousVersion, lock);
} finally {
eventListenerManager.cachePutEnd();
}
}
Aggregations