HHH-13496 Identified and simplified some unnecessary repetition of getter invocations

This commit is contained in:
Sanne Grinovero 2019-07-03 11:41:06 +01:00
parent e7165f2d43
commit 6c44ef12e6
40 changed files with 426 additions and 371 deletions

View File

@ -22,6 +22,7 @@ import org.hibernate.cache.spi.access.NaturalIdDataAccess;
import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.Queryable; import org.hibernate.persister.entity.Queryable;
@ -111,7 +112,8 @@ public class BulkOperationCleanupAction implements Executable, Serializable {
spacesList.addAll( tableSpaces ); spacesList.addAll( tableSpaces );
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
for ( EntityPersister persister : factory.getMetamodel().entityPersisters().values() ) { final MetamodelImplementor metamodel = factory.getMetamodel();
for ( EntityPersister persister : metamodel.entityPersisters().values() ) {
final String[] entitySpaces = (String[]) persister.getQuerySpaces(); final String[] entitySpaces = (String[]) persister.getQuerySpaces();
if ( affectedEntity( tableSpaces, entitySpaces ) ) { if ( affectedEntity( tableSpaces, entitySpaces ) ) {
spacesList.addAll( Arrays.asList( entitySpaces ) ); spacesList.addAll( Arrays.asList( entitySpaces ) );
@ -123,10 +125,10 @@ public class BulkOperationCleanupAction implements Executable, Serializable {
naturalIdCleanups.add( new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy(), session ) ); naturalIdCleanups.add( new NaturalIdCleanup( persister.getNaturalIdCacheAccessStrategy(), session ) );
} }
final Set<String> roles = session.getFactory().getMetamodel().getCollectionRolesByEntityParticipant( persister.getEntityName() ); final Set<String> roles = metamodel.getCollectionRolesByEntityParticipant( persister.getEntityName() );
if ( roles != null ) { if ( roles != null ) {
for ( String role : roles ) { for ( String role : roles ) {
final CollectionPersister collectionPersister = factory.getMetamodel().collectionPersister( role ); final CollectionPersister collectionPersister = metamodel.collectionPersister( role );
if ( collectionPersister.hasCache() ) { if ( collectionPersister.hasCache() ) {
collectionCleanups.add( collectionCleanups.add(
new CollectionCleanup( collectionPersister.getCacheAccessStrategy(), session ) new CollectionCleanup( collectionPersister.getCacheAccessStrategy(), session )

View File

@ -95,7 +95,7 @@ public final class CollectionUpdateAction extends CollectionAction {
final StatisticsImplementor statistics = session.getFactory().getStatistics(); final StatisticsImplementor statistics = session.getFactory().getStatistics();
if ( statistics.isStatisticsEnabled() ) { if ( statistics.isStatisticsEnabled() ) {
statistics.updateCollection( getPersister().getRole() ); statistics.updateCollection( persister.getRole() );
} }
} }

View File

@ -222,8 +222,9 @@ public final class EntityInsertAction extends AbstractEntityInsertAction {
final Object ck = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() ); final Object ck = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() );
final boolean put = cacheAfterInsert( cache, ck ); final boolean put = cacheAfterInsert( cache, ck );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().entityCachePut( if ( put && statistics.isStatisticsEnabled() ) {
statistics.entityCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
cache.getRegion().getName() cache.getRegion().getName()
); );

View File

@ -320,10 +320,11 @@ public final class EntityUpdateAction extends EntityAction {
final EntityPersister persister = getPersister(); final EntityPersister persister = getPersister();
if ( persister.canWriteToCache() ) { if ( persister.canWriteToCache() ) {
final EntityDataAccess cache = persister.getCacheAccessStrategy(); final EntityDataAccess cache = persister.getCacheAccessStrategy();
final SessionFactoryImplementor factory = session.getFactory();
final Object ck = cache.generateCacheKey( final Object ck = cache.generateCacheKey(
getId(), getId(),
persister, persister,
session.getFactory(), factory,
session.getTenantIdentifier() session.getTenantIdentifier()
); );
@ -334,15 +335,16 @@ public final class EntityUpdateAction extends EntityAction {
session.getCacheMode().isPutEnabled() ) { session.getCacheMode().isPutEnabled() ) {
final boolean put = cacheAfterUpdate( cache, ck ); final boolean put = cacheAfterUpdate( cache, ck );
if ( put && getSession().getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
session.getFactory().getStatistics().entityCachePut( if ( put && statistics.isStatisticsEnabled() ) {
statistics.entityCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
getPersister().getCacheAccessStrategy().getRegion().getName() cache.getRegion().getName()
); );
} }
} }
else { else {
cache.unlockItem(session, ck, lock ); cache.unlockItem( session, ck, lock );
} }
} }
postCommitUpdate( success ); postCommitUpdate( success );

View File

@ -13,6 +13,8 @@ import org.hibernate.HibernateException;
import org.hibernate.action.internal.CollectionAction; import org.hibernate.action.internal.CollectionAction;
import org.hibernate.action.spi.AfterTransactionCompletionProcess; import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.spi.access.CollectionDataAccess;
import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -27,9 +29,11 @@ import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.event.spi.PostUpdateEvent; import org.hibernate.event.spi.PostUpdateEvent;
import org.hibernate.event.spi.PostUpdateEventListener; import org.hibernate.event.spi.PostUpdateEventListener;
import org.hibernate.integrator.spi.Integrator; import org.hibernate.integrator.spi.Integrator;
import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.spi.SessionFactoryServiceRegistry; import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -82,11 +86,12 @@ public class CollectionCacheInvalidator
} }
private void integrate(SessionFactoryServiceRegistry serviceRegistry, SessionFactoryImplementor sessionFactory) { private void integrate(SessionFactoryServiceRegistry serviceRegistry, SessionFactoryImplementor sessionFactory) {
if ( !sessionFactory.getSessionFactoryOptions().isAutoEvictCollectionCache() ) { final SessionFactoryOptions sessionFactoryOptions = sessionFactory.getSessionFactoryOptions();
if ( !sessionFactoryOptions.isAutoEvictCollectionCache() ) {
// feature is disabled // feature is disabled
return; return;
} }
if ( !sessionFactory.getSessionFactoryOptions().isSecondLevelCacheEnabled() ) { if ( !sessionFactoryOptions.isSecondLevelCacheEnabled() ) {
// Nothing to do, if caching is disabled // Nothing to do, if caching is disabled
return; return;
} }
@ -100,12 +105,14 @@ public class CollectionCacheInvalidator
try { try {
SessionFactoryImplementor factory = persister.getFactory(); SessionFactoryImplementor factory = persister.getFactory();
Set<String> collectionRoles = factory.getMetamodel().getCollectionRolesByEntityParticipant( persister.getEntityName() ); final MetamodelImplementor metamodel = factory.getMetamodel();
Set<String> collectionRoles = metamodel.getCollectionRolesByEntityParticipant( persister.getEntityName() );
if ( collectionRoles == null || collectionRoles.isEmpty() ) { if ( collectionRoles == null || collectionRoles.isEmpty() ) {
return; return;
} }
final EntityMetamodel entityMetamodel = persister.getEntityMetamodel();
for ( String role : collectionRoles ) { for ( String role : collectionRoles ) {
final CollectionPersister collectionPersister = factory.getMetamodel().collectionPersister( role ); final CollectionPersister collectionPersister = metamodel.collectionPersister( role );
if ( !collectionPersister.hasCache() ) { if ( !collectionPersister.hasCache() ) {
// ignore collection if no caching is used // ignore collection if no caching is used
continue; continue;
@ -114,7 +121,7 @@ public class CollectionCacheInvalidator
String mappedBy = collectionPersister.getMappedByProperty(); String mappedBy = collectionPersister.getMappedByProperty();
if ( !collectionPersister.isManyToMany() && if ( !collectionPersister.isManyToMany() &&
mappedBy != null && !mappedBy.isEmpty() ) { mappedBy != null && !mappedBy.isEmpty() ) {
int i = persister.getEntityMetamodel().getPropertyIndex( mappedBy ); int i = entityMetamodel.getPropertyIndex( mappedBy );
Serializable oldId = null; Serializable oldId = null;
if ( oldState != null ) { if ( oldState != null ) {
// in case of updating an entity we perhaps have to decache 2 entity collections, this is the // in case of updating an entity we perhaps have to decache 2 entity collections, this is the
@ -136,9 +143,10 @@ public class CollectionCacheInvalidator
} }
else { else {
LOG.debug( "Evict CollectionRegion " + role ); LOG.debug( "Evict CollectionRegion " + role );
final SoftLock softLock = collectionPersister.getCacheAccessStrategy().lockRegion(); final CollectionDataAccess cacheAccessStrategy = collectionPersister.getCacheAccessStrategy();
final SoftLock softLock = cacheAccessStrategy.lockRegion();
session.getActionQueue().registerProcess( (success, session1) -> { session.getActionQueue().registerProcess( (success, session1) -> {
collectionPersister.getCacheAccessStrategy().unlockRegion( softLock ); cacheAccessStrategy.unlockRegion( softLock );
} ); } );
} }
} }

View File

@ -11,8 +11,10 @@ import java.io.Serializable;
import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsRegion; import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.TimestampsCache; import org.hibernate.cache.spi.TimestampsCache;
import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -42,28 +44,32 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache {
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
final RegionFactory regionFactory = factory.getCache().getRegionFactory(); final RegionFactory regionFactory = factory.getCache().getRegionFactory();
final boolean stats = factory.getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = factory.getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
final Long ts = regionFactory.nextTimestamp() + regionFactory.getTimeout(); final Long ts = regionFactory.nextTimestamp() + regionFactory.getTimeout();
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
final boolean debugEnabled = log.isDebugEnabled();
for ( Serializable space : spaces ) { for ( Serializable space : spaces ) {
if ( log.isDebugEnabled() ) { if ( debugEnabled ) {
log.debugf( "Pre-invalidating space [%s], timestamp: %s", space, ts ); log.debugf( "Pre-invalidating space [%s], timestamp: %s", space, ts );
} }
try { try {
session.getEventListenerManager().cachePutStart(); eventListenerManager.cachePutStart();
//put() has nowait semantics, is this really appropriate? //put() has nowait semantics, is this really appropriate?
//note that it needs to be async replication, never local or sync //note that it needs to be async replication, never local or sync
timestampsRegion.putIntoCache( space, ts, session ); timestampsRegion.putIntoCache( space, ts, session );
} }
finally { finally {
session.getEventListenerManager().cachePutEnd(); eventListenerManager.cachePutEnd();
} }
if ( stats ) { if ( stats ) {
factory.getStatistics().updateTimestampsCachePut(); statistics.updateTimestampsCachePut();
} }
} }
} }
@ -72,24 +78,27 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache {
public void invalidate( public void invalidate(
String[] spaces, String[] spaces,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = session.getFactory().getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
final Long ts = session.getFactory().getCache().getRegionFactory().nextTimestamp(); final Long ts = session.getFactory().getCache().getRegionFactory().nextTimestamp();
final boolean debugEnabled = log.isDebugEnabled();
for (Serializable space : spaces) { for ( Serializable space : spaces ) {
if ( log.isDebugEnabled() ) { if ( debugEnabled ) {
log.debugf( "Invalidating space [%s], timestamp: %s", space, ts ); log.debugf( "Invalidating space [%s], timestamp: %s", space, ts );
} }
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try { try {
session.getEventListenerManager().cachePutStart(); eventListenerManager.cachePutStart();
timestampsRegion.putIntoCache( space, ts, session ); timestampsRegion.putIntoCache( space, ts, session );
} }
finally { finally {
session.getEventListenerManager().cachePutEnd(); eventListenerManager.cachePutEnd();
if ( stats ) { if ( stats ) {
session.getFactory().getStatistics().updateTimestampsCachePut(); statistics.updateTimestampsCachePut();
} }
} }
} }
@ -100,7 +109,10 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache {
String[] spaces, String[] spaces,
Long timestamp, Long timestamp,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
final StatisticsImplementor statistics = session.getFactory().getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
final boolean debugEnabled = log.isDebugEnabled();
for ( Serializable space : spaces ) { for ( Serializable space : spaces ) {
final Long lastUpdate = getLastUpdateTimestampForSpace( space, session ); final Long lastUpdate = getLastUpdateTimestampForSpace( space, session );
@ -108,11 +120,11 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache {
// the last update timestamp for the given space was evicted from the // the last update timestamp for the given space was evicted from the
// cache or there have been no writes to it since startup // cache or there have been no writes to it since startup
if ( stats ) { if ( stats ) {
session.getFactory().getStatistics().updateTimestampsCacheMiss(); statistics.updateTimestampsCacheMiss();
} }
} }
else { else {
if ( log.isDebugEnabled() ) { if ( debugEnabled ) {
log.debugf( log.debugf(
"[%s] last update timestamp: %s", "[%s] last update timestamp: %s",
space, space,
@ -120,7 +132,7 @@ public class TimestampsCacheEnabledImpl implements TimestampsCache {
); );
} }
if ( stats ) { if ( stats ) {
session.getFactory().getStatistics().updateTimestampsCacheHit(); statistics.updateTimestampsCacheHit();
} }
if ( lastUpdate >= timestamp ) { if ( lastUpdate >= timestamp ) {
return false; return false;

View File

@ -1,47 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.cfg;
import java.util.Set;
import org.hibernate.internal.util.xml.XmlDocument;
/**
* Represents a mapping queued for delayed processing to await
* processing of an extends entity upon which it depends.
*
* @author Steve Ebersole
*/
public class ExtendsQueueEntry {
private final String explicitName;
private final String mappingPackage;
private final XmlDocument metadataXml;
private final Set<String> entityNames;
public ExtendsQueueEntry(String explicitName, String mappingPackage, XmlDocument metadataXml, Set<String> entityNames) {
this.explicitName = explicitName;
this.mappingPackage = mappingPackage;
this.metadataXml = metadataXml;
this.entityNames = entityNames;
}
public String getExplicitName() {
return explicitName;
}
public String getMappingPackage() {
return mappingPackage;
}
public XmlDocument getMetadataXml() {
return metadataXml;
}
public Set<String> getEntityNames() {
return entityNames;
}
}

View File

@ -70,6 +70,7 @@ import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty; import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.model.TypeDefinition; import org.hibernate.boot.model.TypeDefinition;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.AccessType; import org.hibernate.cfg.AccessType;
import org.hibernate.cfg.AnnotatedClassType; import org.hibernate.cfg.AnnotatedClassType;
@ -461,8 +462,9 @@ public abstract class CollectionBinder {
} }
// set explicit type information // set explicit type information
final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector();
if ( explicitType != null ) { if ( explicitType != null ) {
final TypeDefinition typeDef = buildingContext.getMetadataCollector().getTypeDefinition( explicitType ); final TypeDefinition typeDef = metadataCollector.getTypeDefinition( explicitType );
if ( typeDef == null ) { if ( typeDef == null ) {
collection.setTypeName( explicitType ); collection.setTypeName( explicitType );
collection.setTypeParameters( explicitTypeParameters ); collection.setTypeParameters( explicitTypeParameters );
@ -554,7 +556,7 @@ public abstract class CollectionBinder {
//many to many may need some second pass informations //many to many may need some second pass informations
if ( !oneToMany && isMappedBy ) { if ( !oneToMany && isMappedBy ) {
buildingContext.getMetadataCollector().addMappedBy( getCollectionType().getName(), mappedBy, propertyName ); metadataCollector.addMappedBy( getCollectionType().getName(), mappedBy, propertyName );
} }
//TODO reducce tableBinder != null and oneToMany //TODO reducce tableBinder != null and oneToMany
XClass collectionType = getCollectionType(); XClass collectionType = getCollectionType();
@ -580,13 +582,13 @@ public abstract class CollectionBinder {
// do it right away, otherwise @ManyToOne on composite element call addSecondPass // do it right away, otherwise @ManyToOne on composite element call addSecondPass
// and raise a ConcurrentModificationException // and raise a ConcurrentModificationException
//sp.doSecondPass( CollectionHelper.EMPTY_MAP ); //sp.doSecondPass( CollectionHelper.EMPTY_MAP );
buildingContext.getMetadataCollector().addSecondPass( sp, !isMappedBy ); metadataCollector.addSecondPass( sp, !isMappedBy );
} }
else { else {
buildingContext.getMetadataCollector().addSecondPass( sp, !isMappedBy ); metadataCollector.addSecondPass( sp, !isMappedBy );
} }
buildingContext.getMetadataCollector().addCollectionBinding( collection ); metadataCollector.addCollectionBinding( collection );
//property building //property building
PropertyBinder binder = new PropertyBinder(); PropertyBinder binder = new PropertyBinder();

View File

@ -461,10 +461,11 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
@SuppressWarnings({"JavaDoc"}) @SuppressWarnings({"JavaDoc"})
protected boolean isInverseCollectionNoOrphanDelete() { protected boolean isInverseCollectionNoOrphanDelete() {
final CollectionEntry ce = session.getPersistenceContextInternal().getCollectionEntry( this ); final CollectionEntry ce = session.getPersistenceContextInternal().getCollectionEntry( this );
return ce != null if ( ce == null ) {
&& return false;
ce.getLoadedPersister().isInverse() && }
!ce.getLoadedPersister().hasOrphanDelete(); final CollectionPersister loadedPersister = ce.getLoadedPersister();
return loadedPersister.isInverse() && !loadedPersister.hasOrphanDelete();
} }
/** /**
@ -474,9 +475,11 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
@SuppressWarnings({"JavaDoc"}) @SuppressWarnings({"JavaDoc"})
protected boolean isInverseOneToManyOrNoOrphanDelete() { protected boolean isInverseOneToManyOrNoOrphanDelete() {
final CollectionEntry ce = session.getPersistenceContextInternal().getCollectionEntry( this ); final CollectionEntry ce = session.getPersistenceContextInternal().getCollectionEntry( this );
return ce != null if ( ce == null ) {
&& ce.getLoadedPersister().isInverse() return false;
&& ( ce.getLoadedPersister().isOneToMany() || !ce.getLoadedPersister().hasOrphanDelete() ); }
final CollectionPersister loadedPersister = ce.getLoadedPersister();
return loadedPersister.isInverse() && ( loadedPersister.isOneToMany() || !loadedPersister.hasOrphanDelete() );
} }
/** /**

View File

@ -15,11 +15,13 @@ import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.SimpleSelect; import org.hibernate.sql.SimpleSelect;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* A pessimistic locking strategy where the locks are obtained through select statements. * A pessimistic locking strategy where the locks are obtained through select statements.
@ -55,42 +57,45 @@ public class PessimisticReadSelectLockingStrategy extends AbstractSelectLockingS
final String sql = determineSql( timeout ); final String sql = determineSql( timeout );
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
try { try {
final Lockable lockable = getLockable();
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
if ( getLockable().isVersioned() ) { if ( lockable.isVersioned() ) {
getLockable().getVersionType().nullSafeSet( lockable.getVersionType().nullSafeSet(
st, st,
version, version,
getLockable().getIdentifierType().getColumnSpan( factory ) + 1, lockable.getIdentifierType().getColumnSpan( factory ) + 1,
session session
); );
} }
final ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); final ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
if ( !rs.next() ) { if ( !rs.next() ) {
if ( factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( getLockable().getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockable.getEntityName() );
} }
throw new StaleObjectStateException( getLockable().getEntityName(), id ); throw new StaleObjectStateException( lockable.getEntityName(), id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( rs, st );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException e ) { catch ( SQLException e ) {
throw session.getJdbcServices().getSqlExceptionHelper().convert( throw session.getJdbcServices().getSqlExceptionHelper().convert(
e, e,
"could not lock: " + MessageHelper.infoString( getLockable(), id, session.getFactory() ), "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
sql sql
); );
} }

View File

@ -14,12 +14,14 @@ import org.hibernate.HibernateException;
import org.hibernate.JDBCException; import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.Update; import org.hibernate.sql.Update;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -75,7 +77,8 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy {
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
try { try {
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
lockable.getVersionType().nullSafeSet( st, version, 1, session ); lockable.getVersionType().nullSafeSet( st, version, 1, session );
int offset = 2; int offset = 2;
@ -87,19 +90,20 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy {
lockable.getVersionType().nullSafeSet( st, version, offset, session ); lockable.getVersionType().nullSafeSet( st, version, offset, session );
} }
final int affected = session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
// todo: should this instead check for exactly one row modified? // todo: should this instead check for exactly one row modified?
if ( affected < 0 ) { if ( affected < 0 ) {
if (factory.getStatistics().isStatisticsEnabled()) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( lockable.getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockable.getEntityName() );
} }
throw new StaleObjectStateException( lockable.getEntityName(), id ); throw new StaleObjectStateException( lockable.getEntityName(), id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }

View File

@ -15,11 +15,13 @@ import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.SimpleSelect; import org.hibernate.sql.SimpleSelect;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* A pessimistic locking strategy where the locks are obtained through select statements. * A pessimistic locking strategy where the locks are obtained through select statements.
@ -54,41 +56,44 @@ public class PessimisticWriteSelectLockingStrategy extends AbstractSelectLocking
final String sql = determineSql( timeout ); final String sql = determineSql( timeout );
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
try { try {
final Lockable lockable = getLockable();
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
if ( getLockable().isVersioned() ) { if ( lockable.isVersioned() ) {
getLockable().getVersionType().nullSafeSet( lockable.getVersionType().nullSafeSet(
st, st,
version, version,
getLockable().getIdentifierType().getColumnSpan( factory ) + 1, lockable.getIdentifierType().getColumnSpan( factory ) + 1,
session session
); );
} }
final ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); final ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
if ( !rs.next() ) { if ( !rs.next() ) {
if ( factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( getLockable().getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockable.getEntityName() );
} }
throw new StaleObjectStateException( getLockable().getEntityName(), id ); throw new StaleObjectStateException( lockable.getEntityName(), id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( rs, st );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException e ) { catch ( SQLException e ) {
throw session.getJdbcServices().getSqlExceptionHelper().convert( throw session.getJdbcServices().getSqlExceptionHelper().convert(
e, e,
"could not lock: " + MessageHelper.infoString( getLockable(), id, session.getFactory() ), "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
sql sql
); );
} }

View File

@ -14,12 +14,14 @@ import org.hibernate.HibernateException;
import org.hibernate.JDBCException; import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.Update; import org.hibernate.sql.Update;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -74,7 +76,8 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy {
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
try { try {
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
lockable.getVersionType().nullSafeSet( st, version, 1, session ); lockable.getVersionType().nullSafeSet( st, version, 1, session );
int offset = 2; int offset = 2;
@ -86,19 +89,20 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy {
lockable.getVersionType().nullSafeSet( st, version, offset, session ); lockable.getVersionType().nullSafeSet( st, version, offset, session );
} }
final int affected = session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
// todo: should this instead check for exactly one row modified? // todo: should this instead check for exactly one row modified?
if ( affected < 0 ) { if ( affected < 0 ) {
if (factory.getStatistics().isStatisticsEnabled()) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( lockable.getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockable.getEntityName() );
} }
throw new StaleObjectStateException( lockable.getEntityName(), id ); throw new StaleObjectStateException( lockable.getEntityName(), id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException e ) { catch ( SQLException e ) {

View File

@ -15,11 +15,13 @@ import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.SimpleSelect; import org.hibernate.sql.SimpleSelect;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* A locking strategy where the locks are obtained through select statements. * A locking strategy where the locks are obtained through select statements.
@ -53,42 +55,45 @@ public class SelectLockingStrategy extends AbstractSelectLockingStrategy {
SharedSessionContractImplementor session) throws StaleObjectStateException, JDBCException { SharedSessionContractImplementor session) throws StaleObjectStateException, JDBCException {
final String sql = determineSql( timeout ); final String sql = determineSql( timeout );
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
final Lockable lockable = getLockable();
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
if ( getLockable().isVersioned() ) { if ( lockable.isVersioned() ) {
getLockable().getVersionType().nullSafeSet( lockable.getVersionType().nullSafeSet(
st, st,
version, version,
getLockable().getIdentifierType().getColumnSpan( factory ) + 1, lockable.getIdentifierType().getColumnSpan( factory ) + 1,
session session
); );
} }
final ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); final ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
if ( !rs.next() ) { if ( !rs.next() ) {
if ( factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( getLockable().getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockable.getEntityName() );
} }
throw new StaleObjectStateException( getLockable().getEntityName(), id ); throw new StaleObjectStateException( lockable.getEntityName(), id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( rs, st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( rs, st );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException sqle ) { catch ( SQLException sqle ) {
throw session.getJdbcServices().getSqlExceptionHelper().convert( throw session.getJdbcServices().getSqlExceptionHelper().convert(
sqle, sqle,
"could not lock: " + MessageHelper.infoString( getLockable(), id, session.getFactory() ), "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
sql sql
); );
} }

View File

@ -14,12 +14,16 @@ import org.hibernate.HibernateException;
import org.hibernate.JDBCException; import org.hibernate.JDBCException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.StaleObjectStateException; import org.hibernate.StaleObjectStateException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.sql.Update; import org.hibernate.sql.Update;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -70,37 +74,42 @@ public class UpdateLockingStrategy implements LockingStrategy {
Object object, Object object,
int timeout, int timeout,
SharedSessionContractImplementor session) throws StaleObjectStateException, JDBCException { SharedSessionContractImplementor session) throws StaleObjectStateException, JDBCException {
final String lockableEntityName = lockable.getEntityName();
if ( !lockable.isVersioned() ) { if ( !lockable.isVersioned() ) {
throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockableEntityName + "]" );
} }
// todo : should we additionally check the current isolation mode explicitly? // todo : should we additionally check the current isolation mode explicitly?
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
try { try {
final PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sql );
try { try {
lockable.getVersionType().nullSafeSet( st, version, 1, session ); final VersionType lockableVersionType = lockable.getVersionType();
lockableVersionType.nullSafeSet( st, version, 1, session );
int offset = 2; int offset = 2;
lockable.getIdentifierType().nullSafeSet( st, id, offset, session ); final Type lockableIdentifierType = lockable.getIdentifierType();
offset += lockable.getIdentifierType().getColumnSpan( factory ); lockableIdentifierType.nullSafeSet( st, id, offset, session );
offset += lockableIdentifierType.getColumnSpan( factory );
if ( lockable.isVersioned() ) { if ( lockable.isVersioned() ) {
lockable.getVersionType().nullSafeSet( st, version, offset, session ); lockableVersionType.nullSafeSet( st, version, offset, session );
} }
final int affected = session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); final int affected = jdbcCoordinator.getResultSetReturn().executeUpdate( st );
if ( affected < 0 ) { if ( affected < 0 ) {
if (factory.getStatistics().isStatisticsEnabled()) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().optimisticFailure( lockable.getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( lockableEntityName );
} }
throw new StaleObjectStateException( lockable.getEntityName(), id ); throw new StaleObjectStateException( lockableEntityName, id );
} }
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }

View File

@ -21,6 +21,7 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.internal.StatsHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -240,15 +241,20 @@ public class NaturalIdXrefDelegate {
// Try resolution from second-level cache // Try resolution from second-level cache
final NaturalIdDataAccess naturalIdCacheAccessStrategy = persister.getNaturalIdCacheAccessStrategy(); final NaturalIdDataAccess naturalIdCacheAccessStrategy = persister.getNaturalIdCacheAccessStrategy();
final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalIdValues, persister, session() ); final SharedSessionContractImplementor session = session();
final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalIdValues, persister,
session
);
pk = CacheHelper.fromSharedCache( session(), naturalIdCacheKey, naturalIdCacheAccessStrategy ); pk = CacheHelper.fromSharedCache( session, naturalIdCacheKey, naturalIdCacheAccessStrategy );
// Found in second-level cache, store in session cache // Found in second-level cache, store in session cache
final SessionFactoryImplementor factory = session().getFactory(); final SessionFactoryImplementor factory = session.getFactory();
final StatisticsImplementor statistics = factory.getStatistics();
final boolean statisticsEnabled = statistics.isStatisticsEnabled();
if ( pk != null ) { if ( pk != null ) {
if ( factory.getStatistics().isStatisticsEnabled() ) { if ( statisticsEnabled ) {
factory.getStatistics().naturalIdCacheHit( statistics.naturalIdCacheHit(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );
@ -275,8 +281,8 @@ public class NaturalIdXrefDelegate {
entityNaturalIdResolutionCache.pkToNaturalIdMap.put( pk, cachedNaturalId ); entityNaturalIdResolutionCache.pkToNaturalIdMap.put( pk, cachedNaturalId );
entityNaturalIdResolutionCache.naturalIdToPkMap.put( cachedNaturalId, pk ); entityNaturalIdResolutionCache.naturalIdToPkMap.put( cachedNaturalId, pk );
} }
else if ( factory.getStatistics().isStatisticsEnabled() ) { else if ( statisticsEnabled ) {
factory.getStatistics().naturalIdCacheMiss( statistics.naturalIdCacheMiss(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );

View File

@ -64,6 +64,7 @@ import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer; import org.hibernate.proxy.LazyInitializer;
import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.internal.StatsHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.CollectionType; import org.hibernate.type.CollectionType;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -1810,6 +1811,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalIdValues, persister, session ); final Object naturalIdCacheKey = naturalIdCacheAccessStrategy.generateCacheKey( naturalIdValues, persister, session );
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
final StatisticsImplementor statistics = factory.getStatistics();
switch ( source ) { switch ( source ) {
case LOAD: { case LOAD: {
@ -1824,8 +1826,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
null null
); );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { if ( put && statistics.isStatisticsEnabled() ) {
factory.getStatistics().naturalIdCachePut( statistics.naturalIdCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );
@ -1835,8 +1837,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
} }
case INSERT: { case INSERT: {
final boolean put = naturalIdCacheAccessStrategy.insert( session, naturalIdCacheKey, id ); final boolean put = naturalIdCacheAccessStrategy.insert( session, naturalIdCacheKey, id );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { if ( put && statistics.isStatisticsEnabled() ) {
factory.getStatistics().naturalIdCachePut( statistics.naturalIdCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );
@ -1848,8 +1850,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) { public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) {
if (success) { if (success) {
final boolean put = naturalIdCacheAccessStrategy.afterInsert( session, naturalIdCacheKey, id ); final boolean put = naturalIdCacheAccessStrategy.afterInsert( session, naturalIdCacheKey, id );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { if ( put && statistics.isStatisticsEnabled() ) {
factory.getStatistics().naturalIdCachePut( statistics.naturalIdCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );
@ -1875,8 +1877,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
final SoftLock lock = naturalIdCacheAccessStrategy.lockItem( session, naturalIdCacheKey, null ); final SoftLock lock = naturalIdCacheAccessStrategy.lockItem( session, naturalIdCacheKey, null );
final boolean put = naturalIdCacheAccessStrategy.update( session, naturalIdCacheKey, id ); final boolean put = naturalIdCacheAccessStrategy.update( session, naturalIdCacheKey, id );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { if ( put && statistics.isStatisticsEnabled() ) {
factory.getStatistics().naturalIdCachePut( statistics.naturalIdCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );
@ -1895,8 +1897,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
lock lock
); );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { if ( put && statistics.isStatisticsEnabled() ) {
factory.getStatistics().naturalIdCachePut( statistics.naturalIdCachePut(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
naturalIdCacheAccessStrategy.getRegion().getName() naturalIdCacheAccessStrategy.getRegion().getName()
); );

View File

@ -477,8 +477,9 @@ public final class TwoPhaseLoad {
return session.getCacheMode() != CacheMode.REFRESH; return session.getCacheMode() != CacheMode.REFRESH;
} }
else { else {
return entityEntry.getPersister().hasLazyProperties() final EntityPersister persister = entityEntry.getPersister();
&& entityEntry.getPersister().isLazyPropertiesCacheable(); return persister.hasLazyProperties()
&& persister.isLazyPropertiesCacheable();
} }
} }

View File

@ -24,6 +24,7 @@ import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionEntry; import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.Status; import org.hibernate.engine.spi.Status;
@ -34,6 +35,7 @@ import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* Represents state associated with the processing of a given {@link ResultSet} * Represents state associated with the processing of a given {@link ResultSet}
@ -229,21 +231,23 @@ public class CollectionLoadContext {
private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) { private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
LOG.tracev( "Ending loading collection [{0}]", lce ); LOG.tracev( "Ending loading collection [{0}]", lce );
final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession(); final PersistenceContext persistenceContext = getLoadContext().getPersistenceContext();
final SharedSessionContractImplementor session = persistenceContext.getSession();
// warning: can cause a recursive calls! (proxy initialization) // warning: can cause a recursive calls! (proxy initialization)
final boolean hasNoQueuedAdds = lce.getCollection().endRead(); final PersistentCollection loadingCollection = lce.getCollection();
final boolean hasNoQueuedAdds = loadingCollection.endRead();
if ( persister.getCollectionType().hasHolder() ) { if ( persister.getCollectionType().hasHolder() ) {
getLoadContext().getPersistenceContext().addCollectionHolder( lce.getCollection() ); persistenceContext.addCollectionHolder( loadingCollection );
} }
CollectionEntry ce = getLoadContext().getPersistenceContext().getCollectionEntry( lce.getCollection() ); CollectionEntry ce = persistenceContext.getCollectionEntry( loadingCollection );
if ( ce == null ) { if ( ce == null ) {
ce = getLoadContext().getPersistenceContext().addInitializedCollection( persister, lce.getCollection(), lce.getKey() ); ce = persistenceContext.addInitializedCollection( persister, loadingCollection, lce.getKey() );
} }
else { else {
ce.postInitialize( lce.getCollection() ); ce.postInitialize( loadingCollection );
// if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize // if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize
// getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce); // getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce);
// } // }
@ -251,31 +255,32 @@ public class CollectionLoadContext {
// The collection has been completely initialized and added to the PersistenceContext. // The collection has been completely initialized and added to the PersistenceContext.
if ( lce.getCollection().getOwner() != null ) { if ( loadingCollection.getOwner() != null ) {
// If the owner is bytecode-enhanced and the owner's collection value is uninitialized, // If the owner is bytecode-enhanced and the owner's collection value is uninitialized,
// then go ahead and set it to the newly initialized collection. // then go ahead and set it to the newly initialized collection.
final EntityPersister ownerEntityPersister = persister.getOwnerEntityPersister();
final BytecodeEnhancementMetadata bytecodeEnhancementMetadata = final BytecodeEnhancementMetadata bytecodeEnhancementMetadata =
persister.getOwnerEntityPersister().getBytecodeEnhancementMetadata(); ownerEntityPersister.getBytecodeEnhancementMetadata();
if ( bytecodeEnhancementMetadata.isEnhancedForLazyLoading() ) { if ( bytecodeEnhancementMetadata.isEnhancedForLazyLoading() ) {
// Lazy properties in embeddables/composites are not currently supported for embeddables (HHH-10480), // Lazy properties in embeddables/composites are not currently supported for embeddables (HHH-10480),
// so check to make sure the collection is not in an embeddable before checking to see if // so check to make sure the collection is not in an embeddable before checking to see if
// the collection is lazy. // the collection is lazy.
// TODO: More will probably need to be done here when HHH-10480 is fixed.. // TODO: More will probably need to be done here when HHH-10480 is fixed..
if ( StringHelper.qualifier( persister.getRole() ).length() == if ( StringHelper.qualifier( persister.getRole() ).length() ==
persister.getOwnerEntityPersister().getEntityName().length() ) { ownerEntityPersister.getEntityName().length() ) {
// Assume the collection is not in an embeddable. // Assume the collection is not in an embeddable.
// Strip off <entityName><dot> to get the collection property name. // Strip off <entityName><dot> to get the collection property name.
final String propertyName = persister.getRole().substring( final String propertyName = persister.getRole().substring(
persister.getOwnerEntityPersister().getEntityName().length() + 1 ownerEntityPersister.getEntityName().length() + 1
); );
if ( !bytecodeEnhancementMetadata.isAttributeLoaded( lce.getCollection().getOwner(), propertyName ) ) { if ( !bytecodeEnhancementMetadata.isAttributeLoaded( loadingCollection.getOwner(), propertyName ) ) {
int propertyIndex = persister.getOwnerEntityPersister().getEntityMetamodel().getPropertyIndex( int propertyIndex = ownerEntityPersister.getEntityMetamodel().getPropertyIndex(
propertyName propertyName
); );
persister.getOwnerEntityPersister().setPropertyValue( ownerEntityPersister.setPropertyValue(
lce.getCollection().getOwner(), loadingCollection.getOwner(),
propertyIndex, propertyIndex,
lce.getCollection() loadingCollection
); );
} }
} }
@ -297,11 +302,12 @@ public class CollectionLoadContext {
if ( LOG.isDebugEnabled() ) { if ( LOG.isDebugEnabled() ) {
LOG.debugf( LOG.debugf(
"Collection fully initialized: %s", "Collection fully initialized: %s",
MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) MessageHelper.collectionInfoString( persister, loadingCollection, lce.getKey(), session )
); );
} }
if ( session.getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = session.getFactory().getStatistics();
session.getFactory().getStatistics().loadCollection( persister.getRole() ); if ( statistics.isStatisticsEnabled() ) {
statistics.loadCollection( persister.getRole() );
} }
} }
@ -384,8 +390,9 @@ public class CollectionLoadContext {
// CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad // CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
if (isPutFromLoad) { if (isPutFromLoad) {
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try { try {
session.getEventListenerManager().cachePutStart(); eventListenerManager.cachePutStart();
final boolean put = cacheAccess.putFromLoad( final boolean put = cacheAccess.putFromLoad(
session, session,
cacheKey, cacheKey,
@ -394,15 +401,16 @@ public class CollectionLoadContext {
factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
); );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().collectionCachePut( if ( put && statistics.isStatisticsEnabled() ) {
statistics.collectionCachePut(
persister.getNavigableRole(), persister.getNavigableRole(),
persister.getCacheAccessStrategy().getRegion().getName() persister.getCacheAccessStrategy().getRegion().getName()
); );
} }
} }
finally { finally {
session.getEventListenerManager().cachePutEnd(); eventListenerManager.cachePutEnd();
} }
} }
} }

View File

@ -29,6 +29,7 @@ import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.query.ParameterMetadata; import org.hibernate.query.ParameterMetadata;
import org.hibernate.query.internal.ParameterMetadataImpl; import org.hibernate.query.internal.ParameterMetadataImpl;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* Acts as a cache for compiled query plans, as well as query-parameter metadata. * Acts as a cache for compiled query plans, as well as query-parameter metadata.
@ -149,7 +150,8 @@ public class QueryPlanCache implements Serializable {
throws QueryException, MappingException { throws QueryException, MappingException {
final HQLQueryPlanKey key = new HQLQueryPlanKey( queryString, shallow, enabledFilters ); final HQLQueryPlanKey key = new HQLQueryPlanKey( queryString, shallow, enabledFilters );
HQLQueryPlan value = (HQLQueryPlan) queryPlanCache.get( key ); HQLQueryPlan value = (HQLQueryPlan) queryPlanCache.get( key );
boolean stats = factory.getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = factory.getStatistics();
boolean stats = statistics.isStatisticsEnabled();
if ( value == null ) { if ( value == null ) {
final long startTime = ( stats ) ? System.nanoTime() : 0L; final long startTime = ( stats ) ? System.nanoTime() : 0L;
@ -160,7 +162,7 @@ public class QueryPlanCache implements Serializable {
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long microseconds = TimeUnit.MICROSECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long microseconds = TimeUnit.MICROSECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
factory.getStatistics().queryCompiled( queryString, microseconds ); statistics.queryCompiled( queryString, microseconds );
} }
queryPlanCache.putIfAbsent( key, value ); queryPlanCache.putIfAbsent( key, value );
@ -169,7 +171,7 @@ public class QueryPlanCache implements Serializable {
LOG.tracev( "Located HQL query plan in cache ({0})", queryString ); LOG.tracev( "Located HQL query plan in cache ({0})", queryString );
if ( stats ) { if ( stats ) {
factory.getStatistics().queryPlanCacheHit( queryString ); statistics.queryPlanCacheHit( queryString );
} }
} }
return value; return value;
@ -348,15 +350,16 @@ public class QueryPlanCache implements Serializable {
private DynamicFilterKey(FilterImpl filter) { private DynamicFilterKey(FilterImpl filter) {
this.filterName = filter.getName(); this.filterName = filter.getName();
if ( filter.getParameters().isEmpty() ) { final Map<String, ?> parameters = filter.getParameters();
if ( parameters.isEmpty() ) {
parameterMetadata = Collections.emptyMap(); parameterMetadata = Collections.emptyMap();
} }
else { else {
parameterMetadata = new HashMap<String,Integer>( parameterMetadata = new HashMap<String,Integer>(
CollectionHelper.determineProperSizing( filter.getParameters() ), CollectionHelper.determineProperSizing( parameters ),
CollectionHelper.LOAD_FACTOR CollectionHelper.LOAD_FACTOR
); );
for ( Object o : filter.getParameters().entrySet() ) { for ( Object o : parameters.entrySet() ) {
final Map.Entry entry = (Map.Entry) o; final Map.Entry entry = (Map.Entry) o;
final String key = (String) entry.getKey(); final String key = (String) entry.getKey();
final Integer valueCount; final Integer valueCount;

View File

@ -8,11 +8,14 @@ package org.hibernate.event.internal;
import org.hibernate.FlushMode; import org.hibernate.FlushMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.engine.spi.ActionQueue;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.event.spi.AutoFlushEvent; import org.hibernate.event.spi.AutoFlushEvent;
import org.hibernate.event.spi.AutoFlushEventListener; import org.hibernate.event.spi.AutoFlushEventListener;
import org.hibernate.event.spi.EventSource; import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -35,38 +38,41 @@ public class DefaultAutoFlushEventListener extends AbstractFlushingEventListener
*/ */
public void onAutoFlush(AutoFlushEvent event) throws HibernateException { public void onAutoFlush(AutoFlushEvent event) throws HibernateException {
final EventSource source = event.getSession(); final EventSource source = event.getSession();
final SessionEventListenerManager eventListenerManager = source.getEventListenerManager();
try { try {
source.getEventListenerManager().partialFlushStart(); eventListenerManager.partialFlushStart();
if ( flushMightBeNeeded(source) ) { if ( flushMightBeNeeded( source ) ) {
// Need to get the number of collection removals before flushing to executions // Need to get the number of collection removals before flushing to executions
// (because flushing to executions can add collection removal actions to the action queue). // (because flushing to executions can add collection removal actions to the action queue).
final int oldSize = source.getActionQueue().numberOfCollectionRemovals(); final ActionQueue actionQueue = source.getActionQueue();
flushEverythingToExecutions(event); final int oldSize = actionQueue.numberOfCollectionRemovals();
if ( flushIsReallyNeeded(event, source) ) { flushEverythingToExecutions( event );
if ( flushIsReallyNeeded( event, source ) ) {
LOG.trace( "Need to execute flush" ); LOG.trace( "Need to execute flush" );
// note: performExecutions() clears all collectionXxxxtion // note: performExecutions() clears all collectionXxxxtion
// collections (the collection actions) in the session // collections (the collection actions) in the session
performExecutions(source); performExecutions( source );
postFlush(source); postFlush( source );
postPostFlush( source ); postPostFlush( source );
if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = source.getFactory().getStatistics();
source.getFactory().getStatistics().flush(); if ( statistics.isStatisticsEnabled() ) {
statistics.flush();
} }
} }
else { else {
LOG.trace( "Don't need to execute flush" ); LOG.trace( "Don't need to execute flush" );
source.getActionQueue().clearFromFlushNeededCheck( oldSize ); actionQueue.clearFromFlushNeededCheck( oldSize );
} }
event.setFlushRequired( flushIsReallyNeeded( event, source ) ); event.setFlushRequired( flushIsReallyNeeded( event, source ) );
} }
} }
finally { finally {
source.getEventListenerManager().partialFlushEnd( eventListenerManager.partialFlushEnd(
event.getNumberOfEntitiesProcessed(), event.getNumberOfEntitiesProcessed(),
event.getNumberOfEntitiesProcessed() event.getNumberOfEntitiesProcessed()
); );

View File

@ -43,11 +43,12 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
throw new HibernateException( "collection was evicted" ); throw new HibernateException( "collection was evicted" );
} }
if ( !collection.wasInitialized() ) { if ( !collection.wasInitialized() ) {
final CollectionPersister ceLoadedPersister = ce.getLoadedPersister();
if ( LOG.isTraceEnabled() ) { if ( LOG.isTraceEnabled() ) {
LOG.tracev( LOG.tracev(
"Initializing collection {0}", "Initializing collection {0}",
MessageHelper.collectionInfoString( MessageHelper.collectionInfoString(
ce.getLoadedPersister(), ceLoadedPersister,
collection, collection,
ce.getLoadedKey(), ce.getLoadedKey(),
source source
@ -58,7 +59,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
final boolean foundInCache = initializeCollectionFromCache( final boolean foundInCache = initializeCollectionFromCache(
ce.getLoadedKey(), ce.getLoadedKey(),
ce.getLoadedPersister(), ceLoadedPersister,
collection, collection,
source source
); );
@ -72,7 +73,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
if ( LOG.isTraceEnabled() ) { if ( LOG.isTraceEnabled() ) {
LOG.trace( "Collection not cached" ); LOG.trace( "Collection not cached" );
} }
ce.getLoadedPersister().initialize( ce.getLoadedKey(), source ); ceLoadedPersister.initialize( ce.getLoadedKey(), source );
if ( LOG.isTraceEnabled() ) { if ( LOG.isTraceEnabled() ) {
LOG.trace( "Collection initialized" ); LOG.trace( "Collection initialized" );
} }
@ -80,7 +81,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
final StatisticsImplementor statistics = source.getFactory().getStatistics(); final StatisticsImplementor statistics = source.getFactory().getStatistics();
if ( statistics.isStatisticsEnabled() ) { if ( statistics.isStatisticsEnabled() ) {
statistics.fetchCollection( statistics.fetchCollection(
ce.getLoadedPersister().getRole() ceLoadedPersister.getRole()
); );
} }
} }
@ -119,7 +120,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
final SessionFactoryImplementor factory = source.getFactory(); final SessionFactoryImplementor factory = source.getFactory();
final CollectionDataAccess cacheAccessStrategy = persister.getCacheAccessStrategy(); final CollectionDataAccess cacheAccessStrategy = persister.getCacheAccessStrategy();
final Object ck = cacheAccessStrategy.generateCacheKey( id, persister, factory, source.getTenantIdentifier() ); final Object ck = cacheAccessStrategy.generateCacheKey( id, persister, factory, source.getTenantIdentifier() );
final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() ); final Object ce = CacheHelper.fromSharedCache( source, ck, cacheAccessStrategy );
final StatisticsImplementor statistics = factory.getStatistics(); final StatisticsImplementor statistics = factory.getStatistics();
if ( statistics.isStatisticsEnabled() ) { if ( statistics.isStatisticsEnabled() ) {

View File

@ -38,6 +38,7 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer; import org.hibernate.proxy.LazyInitializer;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.TypeHelper; import org.hibernate.type.TypeHelper;
@ -333,8 +334,9 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener impleme
); );
} }
else if ( isVersionChanged( entity, source, persister, target ) ) { else if ( isVersionChanged( entity, source, persister, target ) ) {
if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = source.getFactory().getStatistics();
source.getFactory().getStatistics().optimisticFailure( entityName ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( entityName );
} }
throw new StaleObjectStateException( entityName, id ); throw new StaleObjectStateException( entityName, id );
} }

View File

@ -20,6 +20,7 @@ import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* Defines the default load event listeners used by hibernate for loading entities * Defines the default load event listeners used by hibernate for loading entities
@ -112,7 +113,8 @@ public class DefaultResolveNaturalIdEventListener
protected Serializable loadFromDatasource(final ResolveNaturalIdEvent event) { protected Serializable loadFromDatasource(final ResolveNaturalIdEvent event) {
final EventSource session = event.getSession(); final EventSource session = event.getSession();
final SessionFactoryImplementor factory = session.getFactory(); final SessionFactoryImplementor factory = session.getFactory();
final boolean stats = factory.getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = factory.getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) { if ( stats ) {
startTime = System.nanoTime(); startTime = System.nanoTime();
@ -127,7 +129,7 @@ public class DefaultResolveNaturalIdEventListener
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
factory.getStatistics().naturalIdQueryExecuted( statistics.naturalIdQueryExecuted(
event.getEntityPersister().getRootEntityName(), event.getEntityPersister().getRootEntityName(),
milliseconds milliseconds
); );

View File

@ -94,8 +94,9 @@ public class SQLExceptionConverterFactory {
// First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param... // First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param...
final Constructor[] ctors = converterClass.getDeclaredConstructors(); final Constructor[] ctors = converterClass.getDeclaredConstructors();
for ( Constructor ctor : ctors ) { for ( Constructor ctor : ctors ) {
if ( ctor.getParameterTypes() != null && ctor.getParameterCount() == 1 ) { final Class[] parameterTypes = ctor.getParameterTypes();
if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( ctor.getParameterTypes()[0] ) ) { if ( parameterTypes != null && ctor.getParameterCount() == 1 ) {
if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( parameterTypes[0] ) ) {
try { try {
return (SQLExceptionConverter) ctor.newInstance( violatedConstraintNameExtracter ); return (SQLExceptionConverter) ctor.newInstance( violatedConstraintNameExtracter );
} }

View File

@ -62,6 +62,7 @@ import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.sql.JoinFragment; import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.JoinType; import org.hibernate.sql.JoinType;
import org.hibernate.sql.QuerySelect; import org.hibernate.sql.QuerySelect;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.AssociationType; import org.hibernate.type.AssociationType;
import org.hibernate.type.EntityType; import org.hibernate.type.EntityType;
@ -1045,7 +1046,8 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
public Iterator iterate(QueryParameters queryParameters, EventSource session) public Iterator iterate(QueryParameters queryParameters, EventSource session)
throws HibernateException { throws HibernateException {
boolean stats = session.getFactory().getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = session.getFactory().getStatistics();
boolean stats = statistics.isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) { if ( stats ) {
startTime = System.nanoTime(); startTime = System.nanoTime();
@ -1078,7 +1080,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
session.getFactory().getStatistics().queryExecuted( statistics.queryExecuted(
"HQL: " + queryString, "HQL: " + queryString,
0, 0,
milliseconds milliseconds

View File

@ -14,6 +14,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
@ -22,6 +23,7 @@ import org.hibernate.hql.internal.ast.HqlSqlWalker;
import org.hibernate.hql.internal.ast.tree.AssignmentSpecification; import org.hibernate.hql.internal.ast.tree.AssignmentSpecification;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy; import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.param.ParameterSpecification; import org.hibernate.param.ParameterSpecification;
import org.hibernate.persister.entity.Queryable;
import org.hibernate.sql.Update; import org.hibernate.sql.Update;
/** /**
@ -57,8 +59,9 @@ public abstract class AbstractInlineIdsUpdateHandlerImpl
if ( !values.getIds().isEmpty() ) { if ( !values.getIds().isEmpty() ) {
String[] tableNames = getTargetedQueryable().getConstraintOrderedTableNameClosure(); final Queryable targetedQueryable = getTargetedQueryable();
String[][] columnNames = getTargetedQueryable().getContraintOrderedTableKeyColumnClosure(); String[] tableNames = targetedQueryable.getConstraintOrderedTableNameClosure();
String[][] columnNames = targetedQueryable.getContraintOrderedTableKeyColumnClosure();
String idSubselect = values.toStatement(); String idSubselect = values.toStatement();
@ -85,6 +88,8 @@ public abstract class AbstractInlineIdsUpdateHandlerImpl
} }
} }
final JdbcCoordinator jdbcCoordinator = session
.getJdbcCoordinator();
// Start performing the updates // Start performing the updates
for ( Map.Entry<Integer, String> updateEntry: updates.entrySet()) { for ( Map.Entry<Integer, String> updateEntry: updates.entrySet()) {
int i = updateEntry.getKey(); int i = updateEntry.getKey();
@ -94,8 +99,7 @@ public abstract class AbstractInlineIdsUpdateHandlerImpl
continue; continue;
} }
try { try {
try (PreparedStatement ps = session try (PreparedStatement ps = jdbcCoordinator.getStatementPreparer()
.getJdbcCoordinator().getStatementPreparer()
.prepareStatement( update, false )) { .prepareStatement( update, false )) {
int position = 1; // jdbc params are 1-based int position = 1; // jdbc params are 1-based
if ( assignmentParameterSpecifications[i] != null ) { if ( assignmentParameterSpecifications[i] != null ) {
@ -104,8 +108,7 @@ public abstract class AbstractInlineIdsUpdateHandlerImpl
.bind( ps, queryParameters, session, position ); .bind( ps, queryParameters, session, position );
} }
} }
session jdbcCoordinator.getResultSetReturn()
.getJdbcCoordinator().getResultSetReturn()
.executeUpdate( ps ); .executeUpdate( ps );
} }
} }

View File

@ -10,6 +10,7 @@ import java.io.Serializable;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.PostInsertIdentityPersister; import org.hibernate.id.PostInsertIdentityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
@ -63,8 +64,9 @@ public abstract class AbstractReturningDelegate implements InsertGeneratedIdenti
protected abstract Serializable executeAndExtract(PreparedStatement insert, SharedSessionContractImplementor session) protected abstract Serializable executeAndExtract(PreparedStatement insert, SharedSessionContractImplementor session)
throws SQLException; throws SQLException;
protected void releaseStatement(PreparedStatement insert, SharedSessionContractImplementor session) throws SQLException { protected void releaseStatement(PreparedStatement insert, SharedSessionContractImplementor session) {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( insert ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( insert );
jdbcCoordinator.afterStatementExecution();
} }
} }

View File

@ -11,6 +11,7 @@ import java.sql.Connection;
import org.hibernate.engine.jdbc.spi.ConnectionObserver; import org.hibernate.engine.jdbc.spi.ConnectionObserver;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.stat.spi.StatisticsImplementor;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
@ -24,8 +25,9 @@ public class ConnectionObserverStatsBridge implements ConnectionObserver, Serial
@Override @Override
public void physicalConnectionObtained(Connection connection) { public void physicalConnectionObtained(Connection connection) {
if ( sessionFactory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = sessionFactory.getStatistics();
sessionFactory.getStatistics().connect(); if ( statistics.isStatisticsEnabled() ) {
statistics.connect();
} }
} }
@ -39,8 +41,9 @@ public class ConnectionObserverStatsBridge implements ConnectionObserver, Serial
@Override @Override
public void statementPrepared() { public void statementPrepared() {
if ( sessionFactory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = sessionFactory.getStatistics();
sessionFactory.getStatistics().prepareStatement(); if ( statistics.isStatisticsEnabled() ) {
statistics.prepareStatement();
} }
} }
} }

View File

@ -19,6 +19,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.function.Supplier;
import javax.naming.Reference; import javax.naming.Reference;
import javax.naming.StringRefAddr; import javax.naming.StringRefAddr;
import javax.persistence.EntityGraph; import javax.persistence.EntityGraph;
@ -79,6 +80,7 @@ import org.hibernate.engine.spi.NamedQueryDefinitionBuilder;
import org.hibernate.engine.spi.NamedSQLQueryDefinition; import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinitionBuilder; import org.hibernate.engine.spi.NamedSQLQueryDefinitionBuilder;
import org.hibernate.engine.spi.SessionBuilderImplementor; import org.hibernate.engine.spi.SessionBuilderImplementor;
import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionOwner; import org.hibernate.engine.spi.SessionOwner;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
@ -1110,30 +1112,33 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
} }
// prefer the SF-scoped interceptor, prefer that to any Session-scoped interceptor prototype // prefer the SF-scoped interceptor, prefer that to any Session-scoped interceptor prototype
if ( options.getInterceptor() != null && options.getInterceptor() != EmptyInterceptor.INSTANCE ) { final Interceptor optionsInterceptor = options.getInterceptor();
return options.getInterceptor(); if ( optionsInterceptor != null && optionsInterceptor != EmptyInterceptor.INSTANCE ) {
return optionsInterceptor;
} }
// then check the Session-scoped interceptor prototype // then check the Session-scoped interceptor prototype
if ( options.getStatelessInterceptorImplementor() != null && options.getStatelessInterceptorImplementorSupplier() != null ) { final Class<? extends Interceptor> statelessInterceptorImplementor = options.getStatelessInterceptorImplementor();
final Supplier<? extends Interceptor> statelessInterceptorImplementorSupplier = options.getStatelessInterceptorImplementorSupplier();
if ( statelessInterceptorImplementor != null && statelessInterceptorImplementorSupplier != null ) {
throw new HibernateException( throw new HibernateException(
"A session scoped interceptor class or supplier are allowed, but not both!" ); "A session scoped interceptor class or supplier are allowed, but not both!" );
} }
else if ( options.getStatelessInterceptorImplementor() != null ) { else if ( statelessInterceptorImplementor != null ) {
try { try {
/** /**
* We could remove the getStatelessInterceptorImplementor method and use just the getStatelessInterceptorImplementorSupplier * We could remove the getStatelessInterceptorImplementor method and use just the getStatelessInterceptorImplementorSupplier
* since it can cover both cases when the user has given a Supplier<? extends Interceptor> or just the * since it can cover both cases when the user has given a Supplier<? extends Interceptor> or just the
* Class<? extends Interceptor>, in which case, we simply instantiate the Interceptor when calling the Supplier. * Class<? extends Interceptor>, in which case, we simply instantiate the Interceptor when calling the Supplier.
*/ */
return options.getStatelessInterceptorImplementor().newInstance(); return statelessInterceptorImplementor.newInstance();
} }
catch (InstantiationException | IllegalAccessException e) { catch (InstantiationException | IllegalAccessException e) {
throw new HibernateException( "Could not supply session-scoped SessionFactory Interceptor", e ); throw new HibernateException( "Could not supply session-scoped SessionFactory Interceptor", e );
} }
} }
else if ( options.getStatelessInterceptorImplementorSupplier() != null ) { else if ( statelessInterceptorImplementorSupplier != null ) {
return options.getStatelessInterceptorImplementorSupplier().get(); return statelessInterceptorImplementorSupplier.get();
} }
return null; return null;
@ -1167,20 +1172,22 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
this.sessionOwner = null; this.sessionOwner = null;
// set up default builder values... // set up default builder values...
this.statementInspector = sessionFactory.getSessionFactoryOptions().getStatementInspector(); final SessionFactoryOptions sessionFactoryOptions = sessionFactory.getSessionFactoryOptions();
this.connectionHandlingMode = sessionFactory.getSessionFactoryOptions().getPhysicalConnectionHandlingMode(); this.statementInspector = sessionFactoryOptions.getStatementInspector();
this.autoClose = sessionFactory.getSessionFactoryOptions().isAutoCloseSessionEnabled(); this.connectionHandlingMode = sessionFactoryOptions.getPhysicalConnectionHandlingMode();
this.flushMode = sessionFactory.getSessionFactoryOptions().isFlushBeforeCompletionEnabled() this.autoClose = sessionFactoryOptions.isAutoCloseSessionEnabled();
this.flushMode = sessionFactoryOptions.isFlushBeforeCompletionEnabled()
? FlushMode.AUTO ? FlushMode.AUTO
: FlushMode.MANUAL; : FlushMode.MANUAL;
if ( sessionFactory.getCurrentTenantIdentifierResolver() != null ) { final CurrentTenantIdentifierResolver currentTenantIdentifierResolver = sessionFactory.getCurrentTenantIdentifierResolver();
tenantIdentifier = sessionFactory.getCurrentTenantIdentifierResolver().resolveCurrentTenantIdentifier(); if ( currentTenantIdentifierResolver != null ) {
tenantIdentifier = currentTenantIdentifierResolver.resolveCurrentTenantIdentifier();
} }
this.jdbcTimeZone = sessionFactory.getSessionFactoryOptions().getJdbcTimeZone(); this.jdbcTimeZone = sessionFactoryOptions.getJdbcTimeZone();
listeners = sessionFactory.getSessionFactoryOptions().getBaselineSessionEventsListenerBuilder().buildBaselineList(); listeners = sessionFactoryOptions.getBaselineSessionEventsListenerBuilder().buildBaselineList();
queryParametersValidationEnabled = sessionFactory.getSessionFactoryOptions().isQueryParametersValidationEnabled(); queryParametersValidationEnabled = sessionFactoryOptions.isQueryParametersValidationEnabled();
} }
@ -1287,8 +1294,9 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
log.tracef( "Opening Hibernate Session. tenant=%s, owner=%s", tenantIdentifier, sessionOwner ); log.tracef( "Opening Hibernate Session. tenant=%s, owner=%s", tenantIdentifier, sessionOwner );
final SessionImpl session = new SessionImpl( sessionFactory, this ); final SessionImpl session = new SessionImpl( sessionFactory, this );
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
for ( SessionEventListener listener : listeners ) { for ( SessionEventListener listener : listeners ) {
session.getEventListenerManager().addListener( listener ); eventListenerManager.addListener( listener );
} }
return session; return session;

View File

@ -178,6 +178,7 @@ import org.hibernate.resource.transaction.spi.TransactionCoordinator;
import org.hibernate.resource.transaction.spi.TransactionStatus; import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics; import org.hibernate.stat.SessionStatistics;
import org.hibernate.stat.internal.SessionStatisticsImpl; import org.hibernate.stat.internal.SessionStatisticsImpl;
import org.hibernate.stat.spi.StatisticsImplementor;
import static org.hibernate.cfg.AvailableSettings.JPA_LOCK_SCOPE; import static org.hibernate.cfg.AvailableSettings.JPA_LOCK_SCOPE;
import static org.hibernate.cfg.AvailableSettings.JPA_LOCK_TIMEOUT; import static org.hibernate.cfg.AvailableSettings.JPA_LOCK_TIMEOUT;
@ -257,19 +258,24 @@ public final class SessionImpl
this.autoClose = options.shouldAutoClose(); this.autoClose = options.shouldAutoClose();
this.queryParametersValidationEnabled = options.isQueryParametersValidationEnabled(); this.queryParametersValidationEnabled = options.isQueryParametersValidationEnabled();
this.discardOnClose = getFactory().getSessionFactoryOptions().isReleaseResourcesOnCloseEnabled(); this.discardOnClose = factory.getSessionFactoryOptions().isReleaseResourcesOnCloseEnabled();
if ( options instanceof SharedSessionCreationOptions && ( (SharedSessionCreationOptions) options ).isTransactionCoordinatorShared() ) { if ( options instanceof SharedSessionCreationOptions ) {
final SharedSessionCreationOptions sharedOptions = (SharedSessionCreationOptions) options; final SharedSessionCreationOptions sharedOptions = (SharedSessionCreationOptions) options;
if ( sharedOptions.getTransactionCompletionProcesses() != null ) { final ActionQueue.TransactionCompletionProcesses transactionCompletionProcesses = sharedOptions.getTransactionCompletionProcesses();
actionQueue.setTransactionCompletionProcesses( sharedOptions.getTransactionCompletionProcesses(), true ); if ( sharedOptions.isTransactionCoordinatorShared() && transactionCompletionProcesses != null ) {
actionQueue.setTransactionCompletionProcesses(
transactionCompletionProcesses,
true
);
} }
} }
loadQueryInfluencers = new LoadQueryInfluencers( factory ); loadQueryInfluencers = new LoadQueryInfluencers( factory );
if ( getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
getFactory().getStatistics().openSession(); if ( statistics.isStatisticsEnabled() ) {
statistics.openSession();
} }
// NOTE : pulse() already handles auto-join-ability correctly // NOTE : pulse() already handles auto-join-ability correctly
@ -418,7 +424,8 @@ public final class SessionImpl
} }
// todo : we want this check if usage is JPA, but not native Hibernate usage // todo : we want this check if usage is JPA, but not native Hibernate usage
if ( getSessionFactory().getSessionFactoryOptions().isJpaBootstrap() ) { final SessionFactoryImplementor sessionFactory = getSessionFactory();
if ( sessionFactory.getSessionFactoryOptions().isJpaBootstrap() ) {
// Original hibernate-entitymanager EM#close behavior // Original hibernate-entitymanager EM#close behavior
checkSessionFactoryOpen(); checkSessionFactoryOpen();
checkOpenOrWaitingForAutoClose(); checkOpenOrWaitingForAutoClose();
@ -435,8 +442,9 @@ public final class SessionImpl
super.close(); super.close();
} }
if ( getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = sessionFactory.getStatistics();
getFactory().getStatistics().closeSession(); if ( statistics.isStatisticsEnabled() ) {
statistics.closeSession();
} }
} }
@ -2572,8 +2580,9 @@ public final class SessionImpl
getEventListenerManager().transactionCompletion( successful ); getEventListenerManager().transactionCompletion( successful );
if ( getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = getFactory().getStatistics();
getFactory().getStatistics().endTransaction( successful ); if ( statistics.isStatisticsEnabled() ) {
statistics.endTransaction( successful );
} }
try { try {

View File

@ -312,13 +312,14 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen
// we could not use bytecode proxy, check to see if we can use HibernateProxy // we could not use bytecode proxy, check to see if we can use HibernateProxy
if ( persister.hasProxy() ) { if ( persister.hasProxy() ) {
final Object existingProxy = getPersistenceContext().getProxy( entityKey ); final PersistenceContext persistenceContext = getPersistenceContext();
final Object existingProxy = persistenceContext.getProxy( entityKey );
if ( existingProxy != null ) { if ( existingProxy != null ) {
return getPersistenceContext().narrowProxy( existingProxy, persister, entityKey, null ); return persistenceContext.narrowProxy( existingProxy, persister, entityKey, null );
} }
else { else {
final Object proxy = persister.createProxy( id, this ); final Object proxy = persister.createProxy( id, this );
getPersistenceContext().addProxy( entityKey, proxy ); persistenceContext.addProxy( entityKey, proxy );
return proxy; return proxy;
} }
} }

View File

@ -1,40 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.internal.util.xml;
import java.io.Serializable;
import org.dom4j.Document;
/**
* Basic implemementation of {@link XmlDocument}
*
* @author Steve Ebersole
*/
public class XmlDocumentImpl implements XmlDocument, Serializable {
private final Document documentTree;
private final Origin origin;
public XmlDocumentImpl(Document documentTree, String originType, String originName) {
this( documentTree, new OriginImpl( originType, originName ) );
}
public XmlDocumentImpl(Document documentTree, Origin origin) {
this.documentTree = documentTree;
this.origin = origin;
}
@Override
public Document getDocumentTree() {
return documentTree;
}
@Override
public Origin getOrigin() {
return origin;
}
}

View File

@ -46,6 +46,7 @@ import org.hibernate.dialect.pagination.NoopLimitHandler;
import org.hibernate.engine.internal.CacheHelper; import org.hibernate.engine.internal.CacheHelper;
import org.hibernate.engine.internal.TwoPhaseLoad; import org.hibernate.engine.internal.TwoPhaseLoad;
import org.hibernate.engine.jdbc.ColumnNameCache; import org.hibernate.engine.jdbc.ColumnNameCache;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
@ -83,6 +84,7 @@ import org.hibernate.persister.entity.UniqueKeyLoadable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.query.spi.ScrollableResultsImplementor; import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.transform.CacheableResultTransformer; import org.hibernate.transform.CacheableResultTransformer;
import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.AssociationType; import org.hibernate.type.AssociationType;
@ -968,8 +970,9 @@ public abstract class Loader {
); );
} }
finally { finally {
session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st ); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( st );
jdbcCoordinator.afterStatementExecution();
} }
} }
@ -1545,8 +1548,9 @@ public abstract class Loader {
null null
); );
if ( !versionType.isEqual( version, currentVersion ) ) { if ( !versionType.isEqual( version, currentVersion ) ) {
if ( session.getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = session.getFactory().getStatistics();
session.getFactory().getStatistics().optimisticFailure( persister.getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( persister.getEntityName() );
} }
throw new StaleObjectStateException( persister.getEntityName(), id ); throw new StaleObjectStateException( persister.getEntityName(), id );
} }
@ -2730,12 +2734,13 @@ public abstract class Loader {
persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig ); persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
} }
if ( factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
if ( statistics.isStatisticsEnabled() ) {
if ( result == null ) { if ( result == null ) {
factory.getStatistics().queryCacheMiss( getQueryIdentifier(), queryCache.getRegion().getName() ); statistics.queryCacheMiss( getQueryIdentifier(), queryCache.getRegion().getName() );
} }
else { else {
factory.getStatistics().queryCacheHit( getQueryIdentifier(), queryCache.getRegion().getName() ); statistics.queryCacheHit( getQueryIdentifier(), queryCache.getRegion().getName() );
} }
} }
} }
@ -2761,8 +2766,9 @@ public abstract class Loader {
key.getResultTransformer().getCachedResultTypes( resultTypes ), key.getResultTransformer().getCachedResultTypes( resultTypes ),
session session
); );
if ( put && factory.getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
factory.getStatistics().queryCachePut( getQueryIdentifier(), queryCache.getRegion().getName() ); if ( put && statistics.isStatisticsEnabled() ) {
statistics.queryCachePut( getQueryIdentifier(), queryCache.getRegion().getName() );
} }
} }
} }
@ -2782,7 +2788,8 @@ public abstract class Loader {
final ResultTransformer forcedResultTransformer) final ResultTransformer forcedResultTransformer)
throws HibernateException { throws HibernateException {
final boolean stats = getFactory().getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = getFactory().getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) { if ( stats ) {
startTime = System.nanoTime(); startTime = System.nanoTime();
@ -2803,7 +2810,7 @@ public abstract class Loader {
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
getFactory().getStatistics().queryExecuted( statistics.queryExecuted(
getQueryIdentifier(), getQueryIdentifier(),
result.size(), result.size(),
milliseconds milliseconds
@ -2856,8 +2863,9 @@ public abstract class Loader {
final SharedSessionContractImplementor session) throws HibernateException { final SharedSessionContractImplementor session) throws HibernateException {
checkScrollability(); checkScrollability();
final StatisticsImplementor statistics = getFactory().getStatistics();
final boolean stats = getQueryIdentifier() != null && final boolean stats = getQueryIdentifier() != null &&
getFactory().getStatistics().isStatisticsEnabled(); statistics.isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) { if ( stats ) {
startTime = System.nanoTime(); startTime = System.nanoTime();
@ -2878,7 +2886,7 @@ public abstract class Loader {
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
getFactory().getStatistics().queryExecuted( statistics.queryExecuted(
getQueryIdentifier(), getQueryIdentifier(),
0, 0,
milliseconds milliseconds

View File

@ -40,6 +40,7 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.internal.StatsHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper; import org.hibernate.type.TypeHelper;
@ -192,23 +193,25 @@ public class CacheEntityLoaderHelper extends AbstractLockUpgradeEventListener {
final EntityPersister persister, final EntityPersister persister,
SessionImplementor source) { SessionImplementor source) {
final EntityDataAccess cache = persister.getCacheAccessStrategy(); final EntityDataAccess cache = persister.getCacheAccessStrategy();
final SessionFactoryImplementor factory = source.getFactory();
final Object ck = cache.generateCacheKey( final Object ck = cache.generateCacheKey(
event.getEntityId(), event.getEntityId(),
persister, persister,
source.getFactory(), factory,
source.getTenantIdentifier() source.getTenantIdentifier()
); );
final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() ); final Object ce = CacheHelper.fromSharedCache( source, ck, persister.getCacheAccessStrategy() );
if ( source.getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = factory.getStatistics();
if ( statistics.isStatisticsEnabled() ) {
if ( ce == null ) { if ( ce == null ) {
source.getFactory().getStatistics().entityCacheMiss( statistics.entityCacheMiss(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
cache.getRegion().getName() cache.getRegion().getName()
); );
} }
else { else {
source.getFactory().getStatistics().entityCacheHit( statistics.entityCacheHit(
StatsHelper.INSTANCE.getRootEntityRole( persister ), StatsHelper.INSTANCE.getRootEntityRole( persister ),
cache.getRegion().getName() cache.getRegion().getName()
); );

View File

@ -45,6 +45,7 @@ import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.persister.entity.Queryable; import org.hibernate.persister.entity.Queryable;
import org.hibernate.query.spi.ScrollableResultsImplementor; import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.EntityType; import org.hibernate.type.EntityType;
import org.hibernate.type.Type; import org.hibernate.type.Type;
@ -514,7 +515,8 @@ public class QueryLoader extends BasicLoader {
QueryParameters queryParameters, QueryParameters queryParameters,
EventSource session) throws HibernateException { EventSource session) throws HibernateException {
checkQuery( queryParameters ); checkQuery( queryParameters );
final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled(); final StatisticsImplementor statistics = session.getFactory().getStatistics();
final boolean stats = statistics.isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) { if ( stats ) {
startTime = System.nanoTime(); startTime = System.nanoTime();
@ -545,7 +547,7 @@ public class QueryLoader extends BasicLoader {
if ( stats ) { if ( stats ) {
final long endTime = System.nanoTime(); final long endTime = System.nanoTime();
final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS ); final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
session.getFactory().getStatistics().queryExecuted( statistics.queryExecuted(
// "HQL: " + queryTranslator.getQueryString(), // "HQL: " + queryTranslator.getQueryString(),
getQueryIdentifier(), getQueryIdentifier(),
0, 0,

View File

@ -33,6 +33,7 @@ import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.batch.internal.BasicBatchKey; import org.hibernate.engine.jdbc.batch.internal.BasicBatchKey;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
@ -1301,6 +1302,7 @@ public abstract class AbstractCollectionPersister
try { try {
// create all the new entries // create all the new entries
Iterator entries = collection.entries( this ); Iterator entries = collection.entries( this );
final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
if ( entries.hasNext() ) { if ( entries.hasNext() ) {
Expectation expectation = Expectations.appropriateExpectation( getInsertCheckStyle() ); Expectation expectation = Expectations.appropriateExpectation( getInsertCheckStyle() );
collection.preInsert( this ); collection.preInsert( this );
@ -1323,14 +1325,12 @@ public abstract class AbstractCollectionPersister
expectation expectation
); );
} }
st = session st = jdbcCoordinator
.getJdbcCoordinator()
.getBatch( recreateBatchKey ) .getBatch( recreateBatchKey )
.getBatchStatement( sql, callable ); .getBatchStatement( sql, callable );
} }
else { else {
st = session st = jdbcCoordinator
.getJdbcCoordinator()
.getStatementPreparer() .getStatementPreparer()
.prepareStatement( sql, callable ); .prepareStatement( sql, callable );
} }
@ -1349,13 +1349,13 @@ public abstract class AbstractCollectionPersister
loc = writeElement( st, collection.getElement( entry ), loc, session ); loc = writeElement( st, collection.getElement( entry ), loc, session );
if ( useBatch ) { if ( useBatch ) {
session jdbcCoordinator
.getJdbcCoordinator()
.getBatch( recreateBatchKey ) .getBatch( recreateBatchKey )
.addToBatch(); .addToBatch();
} }
else { else {
expectation.verifyOutcome( session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st ), st, -1 ); expectation.verifyOutcome( jdbcCoordinator
.getResultSetReturn().executeUpdate( st ), st, -1 );
} }
collection.afterRowInsert( this, entry, i ); collection.afterRowInsert( this, entry, i );
@ -1363,14 +1363,14 @@ public abstract class AbstractCollectionPersister
} }
catch ( SQLException sqle ) { catch ( SQLException sqle ) {
if ( useBatch ) { if ( useBatch ) {
session.getJdbcCoordinator().abortBatch(); jdbcCoordinator.abortBatch();
} }
throw sqle; throw sqle;
} }
finally { finally {
if ( !useBatch ) { if ( !useBatch ) {
session.getJdbcCoordinator().getResourceRegistry().release( st ); jdbcCoordinator.getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
@ -1957,23 +1957,23 @@ public abstract class AbstractCollectionPersister
@Override @Override
public int getSize(Serializable key, SharedSessionContractImplementor session) { public int getSize(Serializable key, SharedSessionContractImplementor session) {
try { try {
PreparedStatement st = session final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
.getJdbcCoordinator() PreparedStatement st = jdbcCoordinator
.getStatementPreparer() .getStatementPreparer()
.prepareStatement( sqlSelectSizeString ); .prepareStatement( sqlSelectSizeString );
try { try {
getKeyType().nullSafeSet( st, key, 1, session ); getKeyType().nullSafeSet( st, key, 1, session );
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
return rs.next() ? rs.getInt( 1 ) - baseIndex : 0; return rs.next() ? rs.getInt( 1 ) - baseIndex : 0;
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( rs, st ); jdbcCoordinator.getResourceRegistry().release( rs, st );
} }
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( st ); jdbcCoordinator.getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException sqle ) { catch ( SQLException sqle ) {
@ -1998,27 +1998,27 @@ public abstract class AbstractCollectionPersister
private boolean exists(Serializable key, Object indexOrElement, Type indexOrElementType, String sql, SharedSessionContractImplementor session) { private boolean exists(Serializable key, Object indexOrElement, Type indexOrElementType, String sql, SharedSessionContractImplementor session) {
try { try {
PreparedStatement st = session final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
.getJdbcCoordinator() PreparedStatement st = jdbcCoordinator
.getStatementPreparer() .getStatementPreparer()
.prepareStatement( sql ); .prepareStatement( sql );
try { try {
getKeyType().nullSafeSet( st, key, 1, session ); getKeyType().nullSafeSet( st, key, 1, session );
indexOrElementType.nullSafeSet( st, indexOrElement, keyColumnNames.length + 1, session ); indexOrElementType.nullSafeSet( st, indexOrElement, keyColumnNames.length + 1, session );
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
return rs.next(); return rs.next();
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( rs, st ); jdbcCoordinator.getResourceRegistry().release( rs, st );
} }
} }
catch ( TransientObjectException e ) { catch ( TransientObjectException e ) {
return false; return false;
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( st ); jdbcCoordinator.getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException sqle ) { catch ( SQLException sqle ) {
@ -2034,14 +2034,14 @@ public abstract class AbstractCollectionPersister
@Override @Override
public Object getElementByIndex(Serializable key, Object index, SharedSessionContractImplementor session, Object owner) { public Object getElementByIndex(Serializable key, Object index, SharedSessionContractImplementor session, Object owner) {
try { try {
PreparedStatement st = session final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
.getJdbcCoordinator() PreparedStatement st = jdbcCoordinator
.getStatementPreparer() .getStatementPreparer()
.prepareStatement( sqlSelectRowByIndexString ); .prepareStatement( sqlSelectRowByIndexString );
try { try {
getKeyType().nullSafeSet( st, key, 1, session ); getKeyType().nullSafeSet( st, key, 1, session );
getIndexType().nullSafeSet( st, incrementIndexByBase( index ), keyColumnNames.length + 1, session ); getIndexType().nullSafeSet( st, incrementIndexByBase( index ), keyColumnNames.length + 1, session );
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st ); ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st );
try { try {
if ( rs.next() ) { if ( rs.next() ) {
return getElementType().nullSafeGet( rs, elementColumnAliases, session, owner ); return getElementType().nullSafeGet( rs, elementColumnAliases, session, owner );
@ -2051,12 +2051,12 @@ public abstract class AbstractCollectionPersister
} }
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( rs, st ); jdbcCoordinator.getResourceRegistry().release( rs, st );
} }
} }
finally { finally {
session.getJdbcCoordinator().getResourceRegistry().release( st ); jdbcCoordinator.getResourceRegistry().release( st );
session.getJdbcCoordinator().afterStatementExecution(); jdbcCoordinator.afterStatementExecution();
} }
} }
catch ( SQLException sqle ) { catch ( SQLException sqle ) {

View File

@ -129,6 +129,7 @@ import org.hibernate.sql.SelectFragment;
import org.hibernate.sql.SimpleSelect; import org.hibernate.sql.SimpleSelect;
import org.hibernate.sql.Template; import org.hibernate.sql.Template;
import org.hibernate.sql.Update; import org.hibernate.sql.Update;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.tuple.GenerationTiming; import org.hibernate.tuple.GenerationTiming;
import org.hibernate.tuple.InDatabaseValueGenerationStrategy; import org.hibernate.tuple.InDatabaseValueGenerationStrategy;
import org.hibernate.tuple.InMemoryValueGenerationStrategy; import org.hibernate.tuple.InMemoryValueGenerationStrategy;
@ -2554,8 +2555,9 @@ public abstract class AbstractEntityPersister
} }
catch (StaleStateException e) { catch (StaleStateException e) {
if ( !isNullableTable( tableNumber ) ) { if ( !isNullableTable( tableNumber ) ) {
if ( getFactory().getStatistics().isStatisticsEnabled() ) { final StatisticsImplementor statistics = getFactory().getStatistics();
getFactory().getStatistics().optimisticFailure( getEntityName() ); if ( statistics.isStatisticsEnabled() ) {
statistics.optimisticFailure( getEntityName() );
} }
throw new StaleObjectStateException( getEntityName(), id ); throw new StaleObjectStateException( getEntityName(), id );
} }

View File

@ -946,21 +946,25 @@ public abstract class AbstractProducedQuery<R> implements QueryImplementor<R> {
} }
protected void collectHints(Map<String, Object> hints) { protected void collectHints(Map<String, Object> hints) {
if ( getQueryOptions().getTimeout() != null ) { final RowSelection queryOptions = getQueryOptions();
hints.put( HINT_TIMEOUT, getQueryOptions().getTimeout() ); final Integer queryTimeout = queryOptions.getTimeout();
hints.put( SPEC_HINT_TIMEOUT, getQueryOptions().getTimeout() * 1000 ); if ( queryTimeout != null ) {
hints.put( HINT_TIMEOUT, queryTimeout );
hints.put( SPEC_HINT_TIMEOUT, queryTimeout * 1000 );
} }
if ( getLockOptions().getTimeOut() != WAIT_FOREVER ) { final LockOptions lockOptions = getLockOptions();
hints.put( JPA_LOCK_TIMEOUT, getLockOptions().getTimeOut() ); final int lockOptionsTimeOut = lockOptions.getTimeOut();
if ( lockOptionsTimeOut != WAIT_FOREVER ) {
hints.put( JPA_LOCK_TIMEOUT, lockOptionsTimeOut );
} }
if ( getLockOptions().getScope() ) { if ( lockOptions.getScope() ) {
hints.put( JPA_LOCK_SCOPE, getLockOptions().getScope() ); hints.put( JPA_LOCK_SCOPE, lockOptions.getScope() );
} }
if ( getLockOptions().hasAliasSpecificLockModes() && canApplyAliasSpecificLockModeHints() ) { if ( lockOptions.hasAliasSpecificLockModes() && canApplyAliasSpecificLockModeHints() ) {
for ( Map.Entry<String, LockMode> entry : getLockOptions().getAliasSpecificLocks() ) { for ( Map.Entry<String, LockMode> entry : lockOptions.getAliasSpecificLocks() ) {
hints.put( hints.put(
ALIAS_SPECIFIC_LOCK_MODE + '.' + entry.getKey(), ALIAS_SPECIFIC_LOCK_MODE + '.' + entry.getKey(),
entry.getValue().name() entry.getValue().name()
@ -969,7 +973,7 @@ public abstract class AbstractProducedQuery<R> implements QueryImplementor<R> {
} }
putIfNotNull( hints, HINT_COMMENT, getComment() ); putIfNotNull( hints, HINT_COMMENT, getComment() );
putIfNotNull( hints, HINT_FETCH_SIZE, getQueryOptions().getFetchSize() ); putIfNotNull( hints, HINT_FETCH_SIZE, queryOptions.getFetchSize() );
putIfNotNull( hints, HINT_FLUSH_MODE, getHibernateFlushMode() ); putIfNotNull( hints, HINT_FLUSH_MODE, getHibernateFlushMode() );
if ( cacheStoreMode != null || cacheRetrieveMode != null ) { if ( cacheStoreMode != null || cacheRetrieveMode != null ) {

View File

@ -305,7 +305,8 @@ public abstract class AbstractServiceRegistryImpl
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
private <T extends Service> void processInjection(T service, Method injectionMethod, InjectService injectService) { private <T extends Service> void processInjection(T service, Method injectionMethod, InjectService injectService) {
if ( injectionMethod.getParameterTypes() == null || injectionMethod.getParameterCount() != 1 ) { final Class<?>[] parameterTypes = injectionMethod.getParameterTypes();
if ( parameterTypes == null || injectionMethod.getParameterCount() != 1 ) {
throw new ServiceDependencyException( throw new ServiceDependencyException(
"Encountered @InjectService on method with unexpected number of parameters" "Encountered @InjectService on method with unexpected number of parameters"
); );
@ -313,7 +314,7 @@ public abstract class AbstractServiceRegistryImpl
Class dependentServiceRole = injectService.serviceRole(); Class dependentServiceRole = injectService.serviceRole();
if ( dependentServiceRole == null || dependentServiceRole.equals( Void.class ) ) { if ( dependentServiceRole == null || dependentServiceRole.equals( Void.class ) ) {
dependentServiceRole = injectionMethod.getParameterTypes()[0]; dependentServiceRole = parameterTypes[0];
} }
// todo : because of the use of proxies, this is no longer returning null here... // todo : because of the use of proxies, this is no longer returning null here...