HHH-5697 - Support for multi-tenancy

This commit is contained in:
Steve Ebersole 2011-03-26 09:11:33 -05:00
parent d42d52b8f1
commit fe8c7183d1
31 changed files with 296 additions and 274 deletions

View File

@ -29,7 +29,6 @@ import org.hibernate.AssertionFailure;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.persister.entity.EntityPersister;
@ -183,7 +182,7 @@ public abstract class EntityAction
if ( session != null ) {
this.session = session;
this.persister = session.getFactory().getEntityPersister( entityName );
this.instance = session.getPersistenceContext().getEntity( new EntityKey( id, persister, session.getEntityMode() ) );
this.instance = session.getPersistenceContext().getEntity( session.generateEntityKey( id, persister ) );
}
}
}

View File

@ -188,7 +188,7 @@ public final class EntityIdentityInsertAction extends EntityAction {
if ( !isDelayed ) {
throw new AssertionFailure( "cannot request delayed entity-key for non-delayed post-insert-id generation" );
}
return new EntityKey( getDelayedId(), getPersister(), getSession().getEntityMode() );
return getSession().generateEntityKey( getDelayedId(), getPersister() );
}
@Override

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.engine;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
@ -32,7 +35,6 @@ import org.hibernate.collection.PersistentCollection;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType;
import org.jboss.logging.Logger;
/**
* Implements book-keeping for the collection persistence by reachability algorithm
@ -93,11 +95,7 @@ public final class Collections {
throw new AssertionFailure( "Unable to determine collection owner identifier for orphan-delete processing" );
}
}
EntityKey key = new EntityKey(
ownerId,
loadedPersister.getOwnerEntityPersister(),
session.getEntityMode()
);
EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() );
Object owner = persistenceContext.getEntity(key);
if ( owner == null ) {
throw new AssertionFailure(

View File

@ -22,10 +22,12 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
@ -35,13 +37,11 @@ import org.hibernate.persister.entity.UniqueKeyLoadable;
import org.hibernate.pretty.MessageHelper;
/**
* We need an entry to tell us all about the current state
* of an object with respect to its persistent state
* We need an entry to tell us all about the current state of an object with respect to its persistent state
*
* @author Gavin King
*/
public final class EntityEntry implements Serializable {
private LockMode lockMode;
private Status status;
private Status previousStatus;
@ -52,6 +52,7 @@ public final class EntityEntry implements Serializable {
private Object version;
private transient EntityPersister persister; // for convenience to save some lookups
private final EntityMode entityMode;
private final String tenantId;
private final String entityName;
private transient EntityKey cachedEntityKey; // cached EntityKey (lazy-initialized)
private boolean isBeingReplicated;
@ -68,6 +69,7 @@ public final class EntityEntry implements Serializable {
final boolean existsInDatabase,
final EntityPersister persister,
final EntityMode entityMode,
final String tenantId,
final boolean disableVersionIncrement,
final boolean lazyPropertiesAreUnfetched) {
this.status=status;
@ -83,6 +85,7 @@ public final class EntityEntry implements Serializable {
this.loadedWithLazyPropertiesUnfetched = lazyPropertiesAreUnfetched;
this.persister=persister;
this.entityMode = entityMode;
this.tenantId = tenantId;
this.entityName = persister == null ? null : persister.getEntityName();
}
@ -91,6 +94,7 @@ public final class EntityEntry implements Serializable {
final String entityName,
final Serializable id,
final EntityMode entityMode,
final String tenantId,
final Status status,
final Status previousStatus,
final Object[] loadedState,
@ -105,6 +109,7 @@ public final class EntityEntry implements Serializable {
this.persister = ( factory == null ? null : factory.getEntityPersister( entityName ) );
this.id = id;
this.entityMode = entityMode;
this.tenantId = tenantId;
this.status = status;
this.previousStatus = previousStatus;
this.loadedState = loadedState;
@ -177,7 +182,7 @@ public final class EntityEntry implements Serializable {
if ( getId() == null ) {
throw new IllegalStateException( "cannot generate an EntityKey when id is null.");
}
cachedEntityKey = new EntityKey( getId(), getPersister(), entityMode );
cachedEntityKey = new EntityKey( getId(), getPersister(), entityMode, tenantId );
}
return cachedEntityKey;
}
@ -335,16 +340,17 @@ public final class EntityEntry implements Serializable {
* @throws IOException If a stream error occurs
*/
void serialize(ObjectOutputStream oos) throws IOException {
oos.writeObject( entityName );
oos.writeUTF( entityName );
oos.writeObject( id );
oos.writeObject( entityMode.toString() );
oos.writeObject( status.toString() );
oos.writeObject( ( previousStatus == null ? "" : previousStatus.toString() ) );
oos.writeUTF( entityMode.toString() );
oos.writeUTF( tenantId );
oos.writeUTF( status.toString() );
oos.writeUTF( ( previousStatus == null ? "" : previousStatus.toString() ) );
// todo : potentially look at optimizing these two arrays
oos.writeObject( loadedState );
oos.writeObject( deletedState );
oos.writeObject( version );
oos.writeObject( lockMode.toString() );
oos.writeUTF( lockMode.toString() );
oos.writeBoolean( existsInDatabase );
oos.writeBoolean( isBeingReplicated );
oos.writeBoolean( loadedWithLazyPropertiesUnfetched );
@ -369,10 +375,11 @@ public final class EntityEntry implements Serializable {
String previousStatusString = null;
return new EntityEntry(
( session == null ? null : session.getFactory() ),
( String ) ois.readObject(),
ois.readUTF(),
( Serializable ) ois.readObject(),
EntityMode.parse( ( String ) ois.readObject() ),
Status.parse( ( String ) ois.readObject() ),
EntityMode.parse( ois.readUTF() ),
ois.readUTF(),
Status.parse( ois.readUTF() ),
( ( previousStatusString = ( String ) ois.readObject() ).length() == 0 ?
null :
Status.parse( previousStatusString )
@ -380,7 +387,7 @@ public final class EntityEntry implements Serializable {
( Object[] ) ois.readObject(),
( Object[] ) ois.readObject(),
ois.readObject(),
LockMode.parse( ( String ) ois.readObject() ),
LockMode.parse( ois.readUTF() ),
ois.readBoolean(),
ois.readBoolean(),
ois.readBoolean()

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 20082011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,13 +20,14 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.engine;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.persister.entity.EntityPersister;
@ -36,36 +37,49 @@ import org.hibernate.type.Type;
/**
* Uniquely identifies of an entity instance in a particular session by identifier.
* <p/>
* Uniqueing information consists of the entity-name and the identifier value.
* Information used to determine uniqueness consists of the entity-name and the identifier value (see {@link #equals}).
*
* @see EntityUniqueKey
* @author Gavin King
*/
public final class EntityKey implements Serializable {
private final Serializable identifier;
private final String rootEntityName;
private final String entityName;
private final String rootEntityName;
private final EntityMode entityMode;
private final String tenantId;
private final int hashCode;
private final Type identifierType;
private final boolean isBatchLoadable;
private final SessionFactoryImplementor factory;
private final int hashCode;
private final EntityMode entityMode;
/**
* Construct a unique identifier for an entity class instance
* Construct a unique identifier for an entity class instance.
* <p>
* NOTE : This signature has changed to accommodate both entity mode and multi-tenancy, both of which relate to
* the Session to which this key belongs. To help minimize the impact of these changes in the future, the
* {@link SessionImplementor#generateEntityKey} method was added to hide the session-specific changes.
*
* @param id The entity id
* @param persister The entity persister
* @param entityMode The entity mode of the session to which this key belongs
* @param tenantId The tenant identifier of the session to which this key belongs
*/
public EntityKey(Serializable id, EntityPersister persister, EntityMode entityMode) {
public EntityKey(Serializable id, EntityPersister persister, EntityMode entityMode, String tenantId) {
if ( id == null ) {
throw new AssertionFailure( "null identifier" );
}
this.identifier = id;
this.entityMode = entityMode;
this.rootEntityName = persister.getRootEntityName();
this.entityName = persister.getEntityName();
this.entityMode = entityMode;
this.tenantId = tenantId;
this.identifierType = persister.getIdentifierType();
this.isBatchLoadable = persister.isBatchLoadable();
this.factory = persister.getFactory();
hashCode = generateHashCode(); //cache the hashcode
this.hashCode = generateHashCode();
}
/**
@ -78,6 +92,7 @@ public final class EntityKey implements Serializable {
* @param batchLoadable Whether represented entity is eligible for batch loading
* @param factory The session factory
* @param entityMode The entity's entity mode
* @param tenantId The entity's tenant id (from the session that loaded it).
*/
private EntityKey(
Serializable identifier,
@ -86,7 +101,8 @@ public final class EntityKey implements Serializable {
Type identifierType,
boolean batchLoadable,
SessionFactoryImplementor factory,
EntityMode entityMode) {
EntityMode entityMode,
String tenantId) {
this.identifier = identifier;
this.rootEntityName = rootEntityName;
this.entityName = entityName;
@ -94,16 +110,21 @@ public final class EntityKey implements Serializable {
this.isBatchLoadable = batchLoadable;
this.factory = factory;
this.entityMode = entityMode;
this.tenantId = tenantId;
this.hashCode = generateHashCode();
}
private int generateHashCode() {
int result = 17;
result = 37 * result + rootEntityName.hashCode();
result = 37 * result + identifierType.getHashCode( identifier, entityMode, factory );
return result;
}
public boolean isBatchLoadable() {
return isBatchLoadable;
}
/**
* Get the user-visible identifier
*/
public Serializable getIdentifier() {
return identifier;
}
@ -112,23 +133,19 @@ public final class EntityKey implements Serializable {
return entityName;
}
@Override
public boolean equals(Object other) {
EntityKey otherKey = (EntityKey) other;
return otherKey.rootEntityName.equals(this.rootEntityName) &&
identifierType.isEqual(otherKey.identifier, this.identifier, entityMode, factory);
}
private int generateHashCode() {
int result = 17;
result = 37 * result + rootEntityName.hashCode();
result = 37 * result + identifierType.getHashCode( identifier, entityMode, factory );
return result;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return "EntityKey" +
MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory );
@ -139,15 +156,17 @@ public final class EntityKey implements Serializable {
* Session/PersistenceContext for increased performance.
*
* @param oos The stream to which we should write the serial data.
* @throws IOException
*
* @throws IOException Thrown by Java I/O
*/
void serialize(ObjectOutputStream oos) throws IOException {
oos.writeObject( identifier );
oos.writeObject( rootEntityName );
oos.writeObject( entityName );
oos.writeUTF( rootEntityName );
oos.writeUTF( entityName );
oos.writeObject( identifierType );
oos.writeBoolean( isBatchLoadable );
oos.writeObject( entityMode.toString() );
oos.writeUTF( entityMode.toString() );
oos.writeUTF( tenantId );
}
/**
@ -156,21 +175,24 @@ public final class EntityKey implements Serializable {
*
* @param ois The stream from which to read the entry.
* @param session The session being deserialized.
*
* @return The deserialized EntityEntry
* @throws IOException
* @throws ClassNotFoundException
*
* @throws IOException Thrown by Java I/O
* @throws ClassNotFoundException Thrown by Java I/O
*/
static EntityKey deserialize(
ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException {
return new EntityKey(
( Serializable ) ois.readObject(),
( String ) ois.readObject(),
( String ) ois.readObject(),
ois.readUTF(),
ois.readUTF(),
( Type ) ois.readObject(),
ois.readBoolean(),
( session == null ? null : session.getFactory() ),
EntityMode.parse( ( String ) ois.readObject() )
EntityMode.parse( ois.readUTF() ),
ois.readUTF()
);
}
}

View File

@ -56,6 +56,13 @@ import org.hibernate.type.Type;
* @author Steve Ebersole
*/
public interface SessionImplementor extends Serializable, LobCreationContext {
/**
* Match te method on {@link org.hibernate.Session} and {@link org.hibernate.StatelessSession}
*
* @return The tenant identifier of this session
*/
public String getTenantIdentifier();
/**
* Provides access to JDBC connections
*
@ -63,6 +70,16 @@ public interface SessionImplementor extends Serializable, LobCreationContext {
*/
public JdbcConnectionAccess getJdbcConnectionAccess();
/**
* Hide the changing requirements of entity key creation
*
* @param id The entity id
* @param persister The entity persister
*
* @return The entity key
*/
public EntityKey generateEntityKey(Serializable id, EntityPersister persister);
/**
* Retrieves the interceptor currently in use by this event source.
*

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.engine;
import static org.jboss.logging.Logger.Level.WARN;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
@ -36,8 +34,11 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.AbstractReferenceMap;
import org.apache.commons.collections.map.ReferenceMap;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
@ -57,7 +58,8 @@ import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.tuple.ElementWrapper;
import org.jboss.logging.Logger;
import static org.jboss.logging.Logger.Level.WARN;
/**
* A <tt>PersistenceContext</tt> represents the state of persistent "stuff" which
@ -284,7 +286,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister)
throws HibernateException {
EntityKey key = new EntityKey( id, persister, session.getEntityMode() );
final EntityKey key = session.generateEntityKey( id, persister );
Object cached = entitySnapshotsByKey.get(key);
if (cached!=null) {
return cached==NO_ROW ? null : (Object[]) cached;
@ -499,9 +501,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
existsInDatabase,
persister,
session.getEntityMode(),
session.getTenantIdentifier(),
disableVersionIncrement,
lazyPropertiesAreUnfetched
);
);
entityEntries.put(entity, e);
setHasNonReadOnlyEnties(status);
@ -565,8 +568,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
if ( li.getSession() != this.getSession() ) {
EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
EntityKey key = new EntityKey( li.getIdentifier(), persister, session.getEntityMode() );
final EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
final EntityKey key = session.generateEntityKey( li.getIdentifier(), persister );
// any earlier proxy takes precedence
if ( !proxiesByKey.containsKey( key ) ) {
proxiesByKey.put( key, proxy );
@ -726,7 +729,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
* Get the entity that owns this persistent collection
*/
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException {
return getEntity( new EntityKey( key, collectionPersister.getOwnerEntityPersister(), session.getEntityMode() ) );
return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
/**
@ -1406,7 +1409,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityEntry oldEntry = ( EntityEntry ) entityEntries.remove( entity );
parentsByChild.clear();
EntityKey newKey = new EntityKey( generatedId, oldEntry.getPersister(), getSession().getEntityMode() );
final EntityKey newKey = session.generateEntityKey( generatedId, oldEntry.getPersister() );
addEntity( newKey, entity );
addEntry(
entity,

View File

@ -22,7 +22,11 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.event.def;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.HibernateLogger;
import org.hibernate.LockMode;
import org.hibernate.engine.EntityEntry;
@ -34,7 +38,6 @@ import org.hibernate.event.EventSource;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.TypeHelper;
import org.jboss.logging.Logger;
/**
* A convenience base class for listeners that respond to requests to reassociate an entity
@ -63,8 +66,8 @@ public class AbstractReassociateEventListener implements Serializable {
if (LOG.isTraceEnabled()) LOG.trace("Reassociating transient instance: "
+ MessageHelper.infoString(persister, id, event.getSession().getFactory()));
EventSource source = event.getSession();
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
final EventSource source = event.getSession();
final EntityKey key = source.generateEntityKey( id, persister );
source.getPersistenceContext().checkUniqueness( key, object );

View File

@ -165,11 +165,13 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
EventSource source,
boolean requiresImmediateIdAccess) {
if (LOG.isTraceEnabled()) LOG.trace("Saving " + MessageHelper.infoString(persister, id, source.getFactory()));
if ( LOG.isTraceEnabled() ) {
LOG.trace("Saving " + MessageHelper.infoString(persister, id, source.getFactory()));
}
EntityKey key;
final EntityKey key;
if ( !useIdentityColumn ) {
key = new EntityKey( id, persister, source.getEntityMode() );
key = source.generateEntityKey( id, persister );
Object old = source.getPersistenceContext().getEntity( key );
if ( old != null ) {
if ( source.getPersistenceContext().getEntry( old ).getStatus() == Status.DELETED ) {
@ -300,7 +302,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
LOG.debugf("Executing identity-insert immediately");
source.getActionQueue().execute( insert );
id = insert.getGeneratedId();
key = new EntityKey( id, persister, source.getEntityMode() );
key = source.generateEntityKey( id, persister );
source.getPersistenceContext().checkUniqueness( key, entity );
}
else {

View File

@ -25,6 +25,9 @@ package org.hibernate.event.def;
import java.io.Serializable;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.CacheMode;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -48,7 +51,6 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
import org.jboss.logging.Logger;
/**
* Defines the default delete event listener used by hibernate for deleting entities
@ -112,7 +114,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
);
}
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
final EntityKey key = source.generateEntityKey( id, persister );
persistenceContext.checkUniqueness( key, entity );
@ -255,7 +257,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
// before any callbacks, etc, so subdeletions see that this deletion happened first
persistenceContext.setEntryStatus( entityEntry, Status.DELETED );
EntityKey key = new EntityKey( entityEntry.getId(), persister, session.getEntityMode() );
final EntityKey key = session.generateEntityKey( entityEntry.getId(), persister );
cascadeBeforeDelete( session, persister, entity, entityEntry, transientEntities );

View File

@ -72,7 +72,7 @@ public class DefaultEvictEventListener implements EvictEventListener {
throw new IllegalArgumentException("null identifier");
}
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
final EntityKey key = source.generateEntityKey( id, persister );
persistenceContext.removeProxy( key );
if ( !li.isUninitialized() ) {

View File

@ -558,7 +558,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
return snapshot;
}
// TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
EntityKey entityKey = new EntityKey(id, persister, session.getEntityMode());
final EntityKey entityKey = session.generateEntityKey( id, persister );
return session.getPersistenceContext().getCachedDatabaseSnapshot(entityKey);
}
}

View File

@ -22,7 +22,11 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.event.def;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -54,7 +58,6 @@ import org.hibernate.type.EmbeddedComponentType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
import org.jboss.logging.Logger;
/**
* Defines the default load event listeners used by hibernate for loading entities
@ -137,7 +140,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
}
}
EntityKey keyToLoad = new EntityKey( event.getEntityId(), persister, source.getEntityMode() );
final EntityKey keyToLoad = source.generateEntityKey( event.getEntityId(), persister );
try {
if ( loadType.isNakedEntityReturned() ) {
@ -167,38 +170,19 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
EntityPersister dependentPersister,
EmbeddedComponentType dependentIdType,
EntityPersister parentPersister) {
final EntityKey parentEntityKey = new EntityKey(
event.getEntityId(),
parentPersister,
event.getSession().getEntityMode()
);
final Object parent = doLoad(
event,
parentPersister,
parentEntityKey,
options
);
final EntityKey parentEntityKey = event.getSession().generateEntityKey( event.getEntityId(), parentPersister );
final Object parent = doLoad( event, parentPersister, parentEntityKey, options );
Serializable dependent = (Serializable) dependentIdType.instantiate( parent, event.getSession() );
final Serializable dependent = (Serializable) dependentIdType.instantiate( parent, event.getSession() );
dependentIdType.setPropertyValues( dependent, new Object[] {parent}, event.getSession().getEntityMode() );
final EntityKey dependentEntityKey = new EntityKey(
dependent,
dependentPersister,
event.getSession().getEntityMode()
);
final EntityKey dependentEntityKey = event.getSession().generateEntityKey( dependent, dependentPersister );
event.setEntityId( dependent );
dependent = (Serializable) doLoad(
event,
dependentPersister,
dependentEntityKey,
options
);
event.setResult( dependent );
event.setResult( doLoad( event, dependentPersister, dependentEntityKey, options ) );
}
/**
* Perfoms the load of an entity.
* Performs the load of an entity.
*
* @param event The initiating load request event
* @param persister The persister corresponding to the entity to be loaded
@ -606,7 +590,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
session.instantiate( subclassPersister, id ) : optionalObject;
// make it circular-reference safe
EntityKey entityKey = new EntityKey( id, subclassPersister, session.getEntityMode() );
final EntityKey entityKey = session.generateEntityKey( id, subclassPersister );
TwoPhaseLoad.addUninitializedCachedEntity(
entityKey,
result,

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,14 +20,17 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.event.def;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -37,6 +40,7 @@ import org.hibernate.StaleObjectStateException;
import org.hibernate.TransientObjectException;
import org.hibernate.WrongClassException;
import org.hibernate.bytecode.instrumentation.internal.FieldInterceptionHelper;
import org.hibernate.bytecode.instrumentation.spi.FieldInterceptor;
import org.hibernate.engine.Cascade;
import org.hibernate.engine.CascadingAction;
import org.hibernate.engine.EntityEntry;
@ -46,14 +50,12 @@ import org.hibernate.engine.Status;
import org.hibernate.event.EventSource;
import org.hibernate.event.MergeEvent;
import org.hibernate.event.MergeEventListener;
import org.hibernate.bytecode.instrumentation.spi.FieldInterceptor;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
import org.jboss.logging.Logger;
/**
* Defines the default copy event listener used by hibernate for copying entities
@ -227,8 +229,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
EntityPersister persister = source.getEntityPersister( event.getEntityName(), entity );
Serializable id = persister.getIdentifier( entity, source );
if ( id != null ) {
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
Object managedEntity = source.getPersistenceContext().getEntity( key );
final EntityKey key = source.generateEntityKey( id, persister );
final Object managedEntity = source.getPersistenceContext().getEntity( key );
entry = source.getPersistenceContext().getEntry( managedEntity );
if ( entry != null ) {
// we have specialized case of a detached entity from the
@ -536,29 +538,21 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
if ( entry == null ) {
Serializable id = persister.getIdentifier( entity, source );
if ( id != null ) {
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
Object managedEntity = source.getPersistenceContext().getEntity( key );
final EntityKey key = source.generateEntityKey( id, persister );
final Object managedEntity = source.getPersistenceContext().getEntity( key );
entry = source.getPersistenceContext().getEntry( managedEntity );
}
}
if ( entry == null ) {
// perhaps this should be an exception since it is only ever used
// in the above method?
return false;
}
else {
return entry.isExistsInDatabase();
}
return entry != null && entry.isExistsInDatabase();
}
protected void copyValues(
final EntityPersister persister,
final Object entity,
final Object target,
final SessionImplementor source,
final Map copyCache
) {
final EntityPersister persister,
final Object entity,
final Object target,
final SessionImplementor source,
final Map copyCache) {
final Object[] copiedValues = TypeHelper.replace(
persister.getPropertyValues( entity, source.getEntityMode() ),
persister.getPropertyValues( target, source.getEntityMode() ),
@ -566,7 +560,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
source,
target,
copyCache
);
);
persister.setPropertyValues( target, copiedValues, source.getEntityMode() );
}

View File

@ -25,6 +25,9 @@ package org.hibernate.event.def;
import java.io.Serializable;
import java.util.Map;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
import org.hibernate.PersistentObjectException;
@ -44,7 +47,6 @@ import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Defines the default refresh event listener used by hibernate for refreshing entities
@ -94,7 +96,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener {
id = persister.getIdentifier( object, event.getSession() );
if (LOG.isTraceEnabled()) LOG.trace("Refreshing transient "
+ MessageHelper.infoString(persister, id, source.getFactory()));
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
final EntityKey key = source.generateEntityKey( id, persister );
if ( source.getPersistenceContext().getEntry(key) != null ) {
throw new PersistentObjectException(
"attempted to refresh transient instance when persistent instance was already associated with the Session: " +
@ -119,7 +121,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener {
.cascade( persister, object, refreshedAlready );
if ( e != null ) {
EntityKey key = new EntityKey( id, persister, source.getEntityMode() );
final EntityKey key = source.generateEntityKey( id, persister );
source.getPersistenceContext().removeEntity(key);
if ( persister.hasCollections() ) new EvictVisitor( source ).process(object, persister);
}

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.event.def;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
import org.hibernate.LockMode;
@ -40,7 +43,6 @@ import org.hibernate.event.ReplicateEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Defines the default replicate event listener used by Hibernate to replicate
@ -125,8 +127,7 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp
+ MessageHelper.infoString(persister, id, source.getFactory()));
final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity!
final EntityKey key = regenerate ?
null : new EntityKey( id, persister, source.getEntityMode() );
final EntityKey key = regenerate ? null : source.generateEntityKey( id, persister );
performSaveOrReplicate(
entity,
@ -181,7 +182,7 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp
entity,
( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ),
null,
new EntityKey( id, persister, source.getEntityMode() ),
source.generateEntityKey( id, persister ),
version,
LockMode.NONE,
true,

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.event.def;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -44,7 +47,6 @@ import org.hibernate.event.SaveOrUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.jboss.logging.Logger;
/**
* Defines the default listener used by Hibernate for handling save-update
@ -282,8 +284,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
event.getSession().getFactory()));
final EventSource source = event.getSession();
EntityKey key = new EntityKey(event.getRequestedId(), persister, source.getEntityMode());
final EntityKey key = source.generateEntityKey( event.getRequestedId(), persister );
source.getPersistenceContext().checkUniqueness(key, entity);

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.impl;
@ -28,6 +27,7 @@ import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.MultiTenancyStrategy;
@ -36,13 +36,14 @@ import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import org.hibernate.SessionException;
import org.hibernate.SharedSessionContract;
import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.NamedQueryDefinition;
import org.hibernate.engine.NamedSQLQueryDefinition;
import org.hibernate.engine.QueryParameters;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess;
import org.hibernate.engine.query.HQLQueryPlan;
import org.hibernate.engine.query.NativeSQLQueryPlan;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
@ -50,6 +51,7 @@ import org.hibernate.engine.transaction.spi.TransactionContext;
import org.hibernate.engine.transaction.spi.TransactionEnvironment;
import org.hibernate.jdbc.WorkExecutor;
import org.hibernate.jdbc.WorkExecutorVisitable;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
@ -59,7 +61,6 @@ import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
* @author Gavin King
*/
public abstract class AbstractSessionImpl implements Serializable, SharedSessionContract, SessionImplementor, TransactionContext {
protected transient SessionFactoryImpl factory;
private String tenantIdentifier;
private boolean closed = false;
@ -97,6 +98,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
);
}
@Override
public boolean isClosed() {
return closed;
}
@ -111,6 +113,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
}
}
@Override
public Query getNamedQuery(String queryName) throws MappingException {
errorIfClosed();
NamedQueryDefinition nqd = factory.getNamedQuery( queryName );
@ -142,6 +145,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return query;
}
@Override
public Query getNamedSQLQuery(String queryName) throws MappingException {
errorIfClosed();
NamedSQLQueryDefinition nsqlqd = factory.getNamedSQLQuery( queryName );
@ -168,6 +172,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
if ( nqd.getComment() != null ) query.setComment( nqd.getComment() );
}
@Override
public Query createQuery(String queryString) {
errorIfClosed();
QueryImpl query = new QueryImpl(
@ -179,6 +184,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return query;
}
@Override
public SQLQuery createSQLQuery(String sql) {
errorIfClosed();
SQLQueryImpl query = new SQLQueryImpl(
@ -198,11 +204,13 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return factory.getQueryPlanCache().getNativeSQLQueryPlan( spec );
}
@Override
public List list(NativeSQLQuerySpecification spec, QueryParameters queryParameters)
throws HibernateException {
return listCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters );
}
@Override
public ScrollableResults scroll(NativeSQLQuerySpecification spec, QueryParameters queryParameters)
throws HibernateException {
return scrollCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters );
@ -221,6 +229,11 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
this.tenantIdentifier = identifier;
}
@Override
public EntityKey generateEntityKey(Serializable id, EntityPersister persister) {
return new EntityKey( id, persister, getEntityMode(), getTenantIdentifier() );
}
private transient JdbcConnectionAccess jdbcConnectionAccess;
@Override

View File

@ -1,8 +1,10 @@
/*
* Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -28,6 +30,9 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.CacheMode;
import org.hibernate.ConnectionReleaseMode;
import org.hibernate.Criteria;
@ -72,7 +77,6 @@ import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* @author Gavin King
@ -272,7 +276,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
errorIfClosed();
EntityPersister persister = getFactory().getEntityPersister( entityName );
// first, try to load it from the temp PC associated to this SS
Object loaded = temporaryPersistenceContext.getEntity( new EntityKey( id, persister, getEntityMode() ) );
Object loaded = temporaryPersistenceContext.getEntity( generateEntityKey( id, persister ) );
if ( loaded != null ) {
// we found it in the temp PC. Should indicate we are in the midst of processing a result set
// containing eager fetches via join fetch

View File

@ -36,6 +36,9 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -81,7 +84,6 @@ import org.hibernate.type.AssociationType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
import org.jboss.logging.Logger;
/**
* Abstract superclass of object loading (and querying) strategies. This class implements
@ -588,11 +590,7 @@ public abstract class Loader {
final String optionalEntityName = queryParameters.getOptionalEntityName();
if ( optionalObject != null && optionalEntityName != null ) {
return new EntityKey(
optionalId,
session.getEntityPersister( optionalEntityName, optionalObject ),
session.getEntityMode()
);
return session.generateEntityKey( optionalId, session.getEntityPersister( optionalEntityName, optionalObject ) );
}
else {
return null;
@ -689,7 +687,7 @@ public abstract class Loader {
final int numberOfPersistersToProcess;
final Serializable optionalId = queryParameters.getOptionalId();
if ( isSingleRowLoader() && optionalId != null ) {
keys[ entitySpan - 1 ] = new EntityKey( optionalId, persisters[ entitySpan - 1 ], session.getEntityMode() );
keys[ entitySpan - 1 ] = session.generateEntityKey( optionalId, persisters[ entitySpan - 1 ] );
// skip the last persister below...
numberOfPersistersToProcess = entitySpan - 1;
}
@ -721,7 +719,7 @@ public abstract class Loader {
null
);
// todo : need a way to signal that this key is resolved and its data resolved
keys[targetIndex] = new EntityKey( targetId, persisters[targetIndex], session.getEntityMode() );
keys[targetIndex] = session.generateEntityKey( targetId, persisters[targetIndex] );
}
// this part copied from #getRow, this section could be refactored out
@ -739,7 +737,7 @@ public abstract class Loader {
);
}
else {
object = instanceNotYetLoaded(
instanceNotYetLoaded(
resultSet,
targetIndex,
persisters[targetIndex],
@ -756,7 +754,7 @@ public abstract class Loader {
}
}
final Serializable resolvedId = (Serializable) idType.resolve( hydratedKeyState[i], session, null );
keys[i] = resolvedId == null ? null : new EntityKey( resolvedId, persisters[i], session.getEntityMode() );
keys[i] = resolvedId == null ? null : session.generateEntityKey( resolvedId, persisters[i] );
}
}
@ -1299,9 +1297,7 @@ public abstract class Loader {
if ( idIsResultId ) resultId = id; //use the id passed in
}
return resultId == null ?
null :
new EntityKey( resultId, persister, session.getEntityMode() );
return resultId == null ? null : session.generateEntityKey( resultId, persister );
}
/**

View File

@ -31,6 +31,9 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
@ -85,7 +88,6 @@ import org.hibernate.type.CollectionType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
@ -647,7 +649,7 @@ public abstract class AbstractCollectionPersister
final PersistenceContext persistenceContext = session.getPersistenceContext();
SubselectFetch subselect = persistenceContext.getBatchFetchQueue()
.getSubselect( new EntityKey( key, getOwnerEntityPersister(), session.getEntityMode() ) );
.getSubselect( session.generateEntityKey( key, getOwnerEntityPersister() ) );
if (subselect == null) {
return null;

View File

@ -35,6 +35,9 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
@ -109,7 +112,6 @@ import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
import org.hibernate.type.VersionType;
import org.jboss.logging.Logger;
/**
* Basic functionality for persisting an entity via JDBC
@ -119,7 +121,7 @@ import org.jboss.logging.Logger;
*/
public abstract class AbstractEntityPersister
implements OuterJoinLoadable, Queryable, ClassMetadata, UniqueKeyLoadable,
SQLLoadable, LazyPropertyInitializer, PostInsertIdentityPersister, Lockable {
SQLLoadable, LazyPropertyInitializer, PostInsertIdentityPersister, Lockable {
private static final HibernateLogger LOG = Logger.getMessageLogger(HibernateLogger.class,
AbstractEntityPersister.class.getName());
@ -2868,7 +2870,7 @@ public abstract class AbstractEntityPersister
// first we need to locate the "loaded" state
//
// Note, it potentially could be a proxy, so doAfterTransactionCompletion the location the safe way...
EntityKey key = new EntityKey( id, this, session.getEntityMode() );
final EntityKey key = session.generateEntityKey( id, this );
Object entity = session.getPersistenceContext().getEntity( key );
if ( entity != null ) {
EntityEntry entry = session.getPersistenceContext().getEntry( entity );
@ -4066,7 +4068,7 @@ public abstract class AbstractEntityPersister
if ( !rs.next() ) {
return null;
}
final EntityKey key = new EntityKey( id, this, session.getEntityMode() );
final EntityKey key = session.generateEntityKey( id, this );
Object owner = session.getPersistenceContext().getEntity( key );
for ( int i = 0; i < naturalIdPropertyCount; i++ ) {
snapshot[i] = extractionTypes[i].hydrate( rs, getPropertyAliases( "", naturalIdPropertyIndexes[i] ), session, null );

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,18 +20,19 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.persister.entity;
import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.FlushMode;
import org.hibernate.HibernateLogger;
import org.hibernate.LockOptions;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.impl.AbstractQueryImpl;
import org.hibernate.loader.entity.UniqueEntityLoader;
import org.jboss.logging.Logger;
/**
* Not really a <tt>Loader</tt>, just a wrapper around a
@ -78,10 +79,8 @@ public final class NamedQueryLoader implements UniqueEntityLoader {
query.list();
// now look up the object we are really interested in!
// (this lets us correctly handle proxies and multi-row
// or multi-column queries)
return session.getPersistenceContext()
.getEntity( new EntityKey( id, persister, session.getEntityMode() ) );
// (this lets us correctly handle proxies and multi-row or multi-column queries)
return session.getPersistenceContext().getEntity( session.generateEntityKey( id, persister ) );
}
}

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,11 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.proxy;
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.LazyInitializationException;
import org.hibernate.SessionException;
@ -74,44 +75,32 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
}
}
/**
* {@inheritDoc}
*/
@Override
public final String getEntityName() {
return entityName;
}
/**
* {@inheritDoc}
*/
@Override
public final Serializable getIdentifier() {
return id;
}
/**
* {@inheritDoc}
*/
@Override
public final void setIdentifier(Serializable id) {
this.id = id;
}
/**
* {@inheritDoc}
*/
@Override
public final boolean isUninitialized() {
return !initialized;
}
/**
* {@inheritDoc}
*/
@Override
public final SessionImplementor getSession() {
return session;
}
/**
* {@inheritDoc}
*/
@Override
public final void setSession(SessionImplementor s) throws HibernateException {
if ( s != session ) {
// check for s == null first, since it is least expensive
@ -143,21 +132,17 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
if ( id == null || s == null || entityName == null ) {
return null;
}
return new EntityKey( id, s.getFactory().getEntityPersister( entityName ), s.getEntityMode() );
return s.generateEntityKey( id, s.getFactory().getEntityPersister( entityName ) );
}
/**
* {@inheritDoc}
*/
@Override
public final void unsetSession() {
session = null;
readOnly = false;
readOnlyBeforeAttachedToSession = null;
}
/**
* {@inheritDoc}
*/
@Override
public final void initialize() throws HibernateException {
if (!initialized) {
if ( session==null ) {
@ -205,26 +190,19 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
return null;
}
/**
* Return the underlying persistent object, initializing if necessary
*/
@Override
public final Object getImplementation() {
initialize();
return target;
}
/**
* {@inheritDoc}
*/
@Override
public final void setImplementation(Object target) {
this.target = target;
initialized = true;
}
/**
* Return the underlying persistent object in the given <tt>Session</tt>, or null,
* do not initialize the proxy
*/
@Override
public final Object getImplementation(SessionImplementor s) throws HibernateException {
final EntityKey entityKey = generateEntityKeyOrNull( getIdentifier(), s, getEntityName() );
return ( entityKey == null ? null : s.getPersistenceContext().getEntity( entityKey ) );
@ -241,9 +219,7 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
return target;
}
/**
* {@inheritDoc}
*/
@Override
public final boolean isReadOnlySettingAvailable() {
return ( session != null && ! session.isClosed() );
}
@ -259,17 +235,13 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
}
}
/**
* {@inheritDoc}
*/
@Override
public final boolean isReadOnly() {
errorIfReadOnlySettingNotAvailable();
return readOnly;
}
/**
* {@inheritDoc}
*/
@Override
public final void setReadOnly(boolean readOnly) {
errorIfReadOnlySettingNotAvailable();
// only update if readOnly is different from current setting
@ -330,16 +302,12 @@ public abstract class AbstractLazyInitializer implements LazyInitializer {
this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUnwrap() {
return unwrap;
}
/**
* {@inheritDoc}
*/
@Override
public void setUnwrap(boolean unwrap) {
this.unwrap = unwrap;
}

View File

@ -25,6 +25,7 @@ package org.hibernate.proxy.pojo;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.internal.util.MarkerObject;
@ -107,14 +108,12 @@ public abstract class BasicLazyInitializer extends AbstractLazyInitializer {
}
private Object getReplacement() {
final SessionImplementor session = getSession();
if ( isUninitialized() && session != null && session.isOpen()) {
final EntityKey key = new EntityKey(
final EntityKey key = session.generateEntityKey(
getIdentifier(),
session.getFactory().getEntityPersister( getEntityName() ),
session.getEntityMode()
);
session.getFactory().getEntityPersister( getEntityName() )
);
final Object entity = session.getPersistenceContext().getEntity(key);
if (entity!=null) setImplementation( entity );
}

View File

@ -22,10 +22,14 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.tuple.entity;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
@ -52,7 +56,6 @@ import org.hibernate.type.ComponentType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
@ -402,10 +405,9 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer {
);
}
final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
final EntityKey entityKey = new EntityKey(
final EntityKey entityKey = session.generateEntityKey(
(Serializable) extractedValues[i],
session.getFactory().getEntityPersister( associatedEntityName ),
entityMode
session.getFactory().getEntityPersister( associatedEntityName )
);
// it is conceivable there is a proxy, so check that first
Object association = session.getPersistenceContext().getProxy( entityKey );

View File

@ -22,11 +22,13 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
@ -165,8 +167,8 @@ public class ManyToOneType extends EntityType {
private void scheduleBatchLoadIfNeeded(Serializable id, SessionImplementor session) throws MappingException {
//cannot batch fetch by unique key (property-ref associations)
if ( uniqueKeyPropertyName == null && id != null ) {
EntityPersister persister = session.getFactory().getEntityPersister( getAssociatedEntityName() );
EntityKey entityKey = new EntityKey( id, persister, session.getEntityMode() );
final EntityPersister persister = session.getFactory().getEntityPersister( getAssociatedEntityName() );
final EntityKey entityKey = session.generateEntityKey( id, persister );
if ( !session.getPersistenceContext().containsEntity( entityKey ) ) {
session.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );
}

View File

@ -22,10 +22,12 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.EntityKey;
@ -66,23 +68,15 @@ public class OneToOneType extends EntityType {
}
public boolean isNull(Object owner, SessionImplementor session) {
if ( propertyName != null ) {
EntityPersister ownerPersister = session.getFactory()
.getEntityPersister(entityName);
Serializable id = session.getContextEntityIdentifier(owner);
EntityKey entityKey = new EntityKey( id, ownerPersister, session.getEntityMode() );
return session.getPersistenceContext()
.isPropertyNull( entityKey, getPropertyName() );
final EntityPersister ownerPersister = session.getFactory().getEntityPersister( entityName );
final Serializable id = session.getContextEntityIdentifier( owner );
final EntityKey entityKey = session.generateEntityKey( id, ownerPersister );
return session.getPersistenceContext().isPropertyNull( entityKey, getPropertyName() );
}
else {
return false;
}
}
public int getColumnSpan(Mapping session) throws MappingException {

View File

@ -1,4 +1,3 @@
//$Id: CustomPersister.java 11398 2007-04-10 14:54:07Z steve.ebersole@jboss.com $
package org.hibernate.test.legacy;
import java.io.Serializable;
@ -335,7 +334,7 @@ public class CustomPersister implements EntityPersister {
if (obj!=null) {
clone = (Custom) obj.clone();
TwoPhaseLoad.addUninitializedEntity(
new EntityKey( id, this, session.getEntityMode() ),
session.generateEntityKey( id, this ),
clone,
this,
LockMode.NONE,

View File

@ -25,7 +25,6 @@ package org.hibernate.test.multitenancy.schema;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.MultiTenancyStrategy;
@ -33,7 +32,6 @@ import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.internal.BasicServiceRegistryImpl;
import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
@ -49,7 +47,6 @@ import org.junit.Before;
import org.junit.Test;
import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.BaseUnitTestCase;
/**
@ -112,11 +109,11 @@ public class SchemaBasedMultiTenancyTest extends BaseUnitTestCase {
},
cfg.generateDropSchemaScript( ConnectionProviderBuilder.getCorrespondingDialect() ),
cfg.generateSchemaCreationScript( ConnectionProviderBuilder.getCorrespondingDialect() )
).execute( // so stupid...
false, // do not script the export (write it to file)
true, // do run it against the database
false, // do not *just* perform the drop
false // do not *just* perform the create
).execute( // so stupid...
false, // do not script the export (write it to file)
true, // do run it against the database
false, // do not *just* perform the drop
false // do not *just* perform the create
);
// do the jboss export

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -28,6 +28,7 @@ import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.CacheMode;
import org.hibernate.EntityMode;
import org.hibernate.FlushMode;
@ -44,7 +45,6 @@ import org.hibernate.engine.PersistenceContext;
import org.hibernate.engine.QueryParameters;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.transaction.spi.TransactionCoordinator;
@ -73,11 +73,21 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple
// Delegate methods
@Override
public String getTenantIdentifier() {
return delegate.getTenantIdentifier();
}
@Override
public JdbcConnectionAccess getJdbcConnectionAccess() {
return delegate.getJdbcConnectionAccess();
}
@Override
public EntityKey generateEntityKey(Serializable id, EntityPersister persister) {
return delegate.generateEntityKey( id, persister );
}
@Override
public <T> T execute(Callback<T> callback) {
return delegate.execute( callback );