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.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess; import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable; import org.hibernate.action.spi.Executable;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.SessionImplementor;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
@ -183,7 +182,7 @@ public abstract class EntityAction
if ( session != null ) { if ( session != null ) {
this.session = session; this.session = session;
this.persister = session.getFactory().getEntityPersister( entityName ); 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 ) { if ( !isDelayed ) {
throw new AssertionFailure( "cannot request delayed entity-key for non-delayed post-insert-id generation" ); 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 @Override

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.engine; package org.hibernate.engine;
import java.io.Serializable; import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode; import org.hibernate.EntityMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
@ -32,7 +35,6 @@ import org.hibernate.collection.PersistentCollection;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType; import org.hibernate.type.CollectionType;
import org.jboss.logging.Logger;
/** /**
* Implements book-keeping for the collection persistence by reachability algorithm * 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" ); throw new AssertionFailure( "Unable to determine collection owner identifier for orphan-delete processing" );
} }
} }
EntityKey key = new EntityKey( EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() );
ownerId,
loadedPersister.getOwnerEntityPersister(),
session.getEntityMode()
);
Object owner = persistenceContext.getEntity(key); Object owner = persistenceContext.getEntity(key);
if ( owner == null ) { if ( owner == null ) {
throw new AssertionFailure( throw new AssertionFailure(

View File

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

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,13 +20,14 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.engine; package org.hibernate.engine;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode; import org.hibernate.EntityMode;
import org.hibernate.persister.entity.EntityPersister; 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. * Uniquely identifies of an entity instance in a particular session by identifier.
* <p/> * <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 * @author Gavin King
*/ */
public final class EntityKey implements Serializable { public final class EntityKey implements Serializable {
private final Serializable identifier; private final Serializable identifier;
private final String rootEntityName;
private final String entityName; 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 Type identifierType;
private final boolean isBatchLoadable; private final boolean isBatchLoadable;
private final SessionFactoryImplementor factory; 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 ) { if ( id == null ) {
throw new AssertionFailure( "null identifier" ); throw new AssertionFailure( "null identifier" );
} }
this.identifier = id; this.identifier = id;
this.entityMode = entityMode;
this.rootEntityName = persister.getRootEntityName(); this.rootEntityName = persister.getRootEntityName();
this.entityName = persister.getEntityName(); this.entityName = persister.getEntityName();
this.entityMode = entityMode;
this.tenantId = tenantId;
this.identifierType = persister.getIdentifierType(); this.identifierType = persister.getIdentifierType();
this.isBatchLoadable = persister.isBatchLoadable(); this.isBatchLoadable = persister.isBatchLoadable();
this.factory = persister.getFactory(); 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 batchLoadable Whether represented entity is eligible for batch loading
* @param factory The session factory * @param factory The session factory
* @param entityMode The entity's entity mode * @param entityMode The entity's entity mode
* @param tenantId The entity's tenant id (from the session that loaded it).
*/ */
private EntityKey( private EntityKey(
Serializable identifier, Serializable identifier,
@ -86,7 +101,8 @@ public final class EntityKey implements Serializable {
Type identifierType, Type identifierType,
boolean batchLoadable, boolean batchLoadable,
SessionFactoryImplementor factory, SessionFactoryImplementor factory,
EntityMode entityMode) { EntityMode entityMode,
String tenantId) {
this.identifier = identifier; this.identifier = identifier;
this.rootEntityName = rootEntityName; this.rootEntityName = rootEntityName;
this.entityName = entityName; this.entityName = entityName;
@ -94,30 +110,10 @@ public final class EntityKey implements Serializable {
this.isBatchLoadable = batchLoadable; this.isBatchLoadable = batchLoadable;
this.factory = factory; this.factory = factory;
this.entityMode = entityMode; this.entityMode = entityMode;
this.tenantId = tenantId;
this.hashCode = generateHashCode(); this.hashCode = generateHashCode();
} }
public boolean isBatchLoadable() {
return isBatchLoadable;
}
/**
* Get the user-visible identifier
*/
public Serializable getIdentifier() {
return identifier;
}
public String getEntityName() {
return entityName;
}
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() { private int generateHashCode() {
int result = 17; int result = 17;
result = 37 * result + rootEntityName.hashCode(); result = 37 * result + rootEntityName.hashCode();
@ -125,10 +121,31 @@ public final class EntityKey implements Serializable {
return result; return result;
} }
public boolean isBatchLoadable() {
return isBatchLoadable;
}
public Serializable getIdentifier() {
return identifier;
}
public String getEntityName() {
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);
}
@Override
public int hashCode() { public int hashCode() {
return hashCode; return hashCode;
} }
@Override
public String toString() { public String toString() {
return "EntityKey" + return "EntityKey" +
MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory ); MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory );
@ -139,15 +156,17 @@ public final class EntityKey implements Serializable {
* Session/PersistenceContext for increased performance. * Session/PersistenceContext for increased performance.
* *
* @param oos The stream to which we should write the serial data. * @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 { void serialize(ObjectOutputStream oos) throws IOException {
oos.writeObject( identifier ); oos.writeObject( identifier );
oos.writeObject( rootEntityName ); oos.writeUTF( rootEntityName );
oos.writeObject( entityName ); oos.writeUTF( entityName );
oos.writeObject( identifierType ); oos.writeObject( identifierType );
oos.writeBoolean( isBatchLoadable ); 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 ois The stream from which to read the entry.
* @param session The session being deserialized. * @param session The session being deserialized.
*
* @return The deserialized EntityEntry * @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( static EntityKey deserialize(
ObjectInputStream ois, ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException { SessionImplementor session) throws IOException, ClassNotFoundException {
return new EntityKey( return new EntityKey(
( Serializable ) ois.readObject(), ( Serializable ) ois.readObject(),
( String ) ois.readObject(), ois.readUTF(),
( String ) ois.readObject(), ois.readUTF(),
( Type ) ois.readObject(), ( Type ) ois.readObject(),
ois.readBoolean(), ois.readBoolean(),
( session == null ? null : session.getFactory() ), ( 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 * @author Steve Ebersole
*/ */
public interface SessionImplementor extends Serializable, LobCreationContext { 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 * Provides access to JDBC connections
* *
@ -63,6 +70,16 @@ public interface SessionImplementor extends Serializable, LobCreationContext {
*/ */
public JdbcConnectionAccess getJdbcConnectionAccess(); 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. * Retrieves the interceptor currently in use by this event source.
* *

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.engine; package org.hibernate.engine;
import static org.jboss.logging.Logger.Level.WARN;
import java.io.IOException; import java.io.IOException;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
@ -36,8 +34,11 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.collections.map.AbstractReferenceMap; import org.apache.commons.collections.map.AbstractReferenceMap;
import org.apache.commons.collections.map.ReferenceMap; import org.apache.commons.collections.map.ReferenceMap;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
@ -57,7 +58,8 @@ 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.tuple.ElementWrapper; 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 * 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) public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister)
throws HibernateException { throws HibernateException {
EntityKey key = new EntityKey( id, persister, session.getEntityMode() ); final EntityKey key = session.generateEntityKey( id, persister );
Object cached = entitySnapshotsByKey.get(key); Object cached = entitySnapshotsByKey.get(key);
if (cached!=null) { if (cached!=null) {
return cached==NO_ROW ? null : (Object[]) cached; return cached==NO_ROW ? null : (Object[]) cached;
@ -499,6 +501,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
existsInDatabase, existsInDatabase,
persister, persister,
session.getEntityMode(), session.getEntityMode(),
session.getTenantIdentifier(),
disableVersionIncrement, disableVersionIncrement,
lazyPropertiesAreUnfetched lazyPropertiesAreUnfetched
); );
@ -565,8 +568,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/ */
private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) { private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
if ( li.getSession() != this.getSession() ) { if ( li.getSession() != this.getSession() ) {
EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() ); final EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
EntityKey key = new EntityKey( li.getIdentifier(), persister, session.getEntityMode() ); final EntityKey key = session.generateEntityKey( li.getIdentifier(), persister );
// any earlier proxy takes precedence // any earlier proxy takes precedence
if ( !proxiesByKey.containsKey( key ) ) { if ( !proxiesByKey.containsKey( key ) ) {
proxiesByKey.put( key, proxy ); proxiesByKey.put( key, proxy );
@ -726,7 +729,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
* Get the entity that owns this persistent collection * Get the entity that owns this persistent collection
*/ */
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException { 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 ); EntityEntry oldEntry = ( EntityEntry ) entityEntries.remove( entity );
parentsByChild.clear(); parentsByChild.clear();
EntityKey newKey = new EntityKey( generatedId, oldEntry.getPersister(), getSession().getEntityMode() ); final EntityKey newKey = session.generateEntityKey( generatedId, oldEntry.getPersister() );
addEntity( newKey, entity ); addEntity( newKey, entity );
addEntry( addEntry(
entity, entity,

View File

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

View File

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

View File

@ -25,6 +25,9 @@ package org.hibernate.event.def;
import java.io.Serializable; import java.io.Serializable;
import java.util.Set; import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger; import org.hibernate.HibernateLogger;
@ -48,7 +51,6 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper; import org.hibernate.type.TypeHelper;
import org.jboss.logging.Logger;
/** /**
* Defines the default delete event listener used by hibernate for deleting entities * 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 ); 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 // before any callbacks, etc, so subdeletions see that this deletion happened first
persistenceContext.setEntryStatus( entityEntry, Status.DELETED ); 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 ); cascadeBeforeDelete( session, persister, entity, entityEntry, transientEntities );

View File

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

View File

@ -558,7 +558,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
return snapshot; return snapshot;
} }
// TODO: optimize away this lookup for entities w/o unsaved-value="undefined" // 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); return session.getPersistenceContext().getCachedDatabaseSnapshot(entityKey);
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.event.def; package org.hibernate.event.def;
import java.io.Serializable; import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger; import org.hibernate.HibernateLogger;
import org.hibernate.LockMode; import org.hibernate.LockMode;
@ -40,7 +43,6 @@ import org.hibernate.event.ReplicateEventListener;
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.type.Type; import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/** /**
* Defines the default replicate event listener used by Hibernate to replicate * 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())); + MessageHelper.infoString(persister, id, source.getFactory()));
final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity! final boolean regenerate = persister.isIdentifierAssignedByInsert(); // prefer re-generation of identity!
final EntityKey key = regenerate ? final EntityKey key = regenerate ? null : source.generateEntityKey( id, persister );
null : new EntityKey( id, persister, source.getEntityMode() );
performSaveOrReplicate( performSaveOrReplicate(
entity, entity,
@ -181,7 +182,7 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp
entity, entity,
( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ), ( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ),
null, null,
new EntityKey( id, persister, source.getEntityMode() ), source.generateEntityKey( id, persister ),
version, version,
LockMode.NONE, LockMode.NONE,
true, true,

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,13 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.event.def; package org.hibernate.event.def;
import java.io.Serializable; import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger; import org.hibernate.HibernateLogger;
@ -44,7 +47,6 @@ import org.hibernate.event.SaveOrUpdateEventListener;
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.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.jboss.logging.Logger;
/** /**
* Defines the default listener used by Hibernate for handling save-update * Defines the default listener used by Hibernate for handling save-update
@ -282,8 +284,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
event.getSession().getFactory())); event.getSession().getFactory()));
final EventSource source = event.getSession(); final EventSource source = event.getSession();
final EntityKey key = source.generateEntityKey( event.getRequestedId(), persister );
EntityKey key = new EntityKey(event.getRequestedId(), persister, source.getEntityMode());
source.getPersistenceContext().checkUniqueness(key, entity); source.getPersistenceContext().checkUniqueness(key, entity);

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate.impl; package org.hibernate.impl;
@ -28,6 +27,7 @@ import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.MultiTenancyStrategy; import org.hibernate.MultiTenancyStrategy;
@ -36,13 +36,14 @@ import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults; import org.hibernate.ScrollableResults;
import org.hibernate.SessionException; import org.hibernate.SessionException;
import org.hibernate.SharedSessionContract; 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.NamedQueryDefinition;
import org.hibernate.engine.NamedSQLQueryDefinition; import org.hibernate.engine.NamedSQLQueryDefinition;
import org.hibernate.engine.QueryParameters; import org.hibernate.engine.QueryParameters;
import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.jdbc.LobCreationContext; import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess;
import org.hibernate.engine.query.HQLQueryPlan; import org.hibernate.engine.query.HQLQueryPlan;
import org.hibernate.engine.query.NativeSQLQueryPlan; import org.hibernate.engine.query.NativeSQLQueryPlan;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; 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.engine.transaction.spi.TransactionEnvironment;
import org.hibernate.jdbc.WorkExecutor; import org.hibernate.jdbc.WorkExecutor;
import org.hibernate.jdbc.WorkExecutorVisitable; 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.ConnectionProvider;
import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider; import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
@ -59,7 +61,6 @@ import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
* @author Gavin King * @author Gavin King
*/ */
public abstract class AbstractSessionImpl implements Serializable, SharedSessionContract, SessionImplementor, TransactionContext { public abstract class AbstractSessionImpl implements Serializable, SharedSessionContract, SessionImplementor, TransactionContext {
protected transient SessionFactoryImpl factory; protected transient SessionFactoryImpl factory;
private String tenantIdentifier; private String tenantIdentifier;
private boolean closed = false; private boolean closed = false;
@ -97,6 +98,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
); );
} }
@Override
public boolean isClosed() { public boolean isClosed() {
return closed; return closed;
} }
@ -111,6 +113,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
} }
} }
@Override
public Query getNamedQuery(String queryName) throws MappingException { public Query getNamedQuery(String queryName) throws MappingException {
errorIfClosed(); errorIfClosed();
NamedQueryDefinition nqd = factory.getNamedQuery( queryName ); NamedQueryDefinition nqd = factory.getNamedQuery( queryName );
@ -142,6 +145,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return query; return query;
} }
@Override
public Query getNamedSQLQuery(String queryName) throws MappingException { public Query getNamedSQLQuery(String queryName) throws MappingException {
errorIfClosed(); errorIfClosed();
NamedSQLQueryDefinition nsqlqd = factory.getNamedSQLQuery( queryName ); NamedSQLQueryDefinition nsqlqd = factory.getNamedSQLQuery( queryName );
@ -168,6 +172,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
if ( nqd.getComment() != null ) query.setComment( nqd.getComment() ); if ( nqd.getComment() != null ) query.setComment( nqd.getComment() );
} }
@Override
public Query createQuery(String queryString) { public Query createQuery(String queryString) {
errorIfClosed(); errorIfClosed();
QueryImpl query = new QueryImpl( QueryImpl query = new QueryImpl(
@ -179,6 +184,7 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return query; return query;
} }
@Override
public SQLQuery createSQLQuery(String sql) { public SQLQuery createSQLQuery(String sql) {
errorIfClosed(); errorIfClosed();
SQLQueryImpl query = new SQLQueryImpl( SQLQueryImpl query = new SQLQueryImpl(
@ -198,11 +204,13 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
return factory.getQueryPlanCache().getNativeSQLQueryPlan( spec ); return factory.getQueryPlanCache().getNativeSQLQueryPlan( spec );
} }
@Override
public List list(NativeSQLQuerySpecification spec, QueryParameters queryParameters) public List list(NativeSQLQuerySpecification spec, QueryParameters queryParameters)
throws HibernateException { throws HibernateException {
return listCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters ); return listCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters );
} }
@Override
public ScrollableResults scroll(NativeSQLQuerySpecification spec, QueryParameters queryParameters) public ScrollableResults scroll(NativeSQLQuerySpecification spec, QueryParameters queryParameters)
throws HibernateException { throws HibernateException {
return scrollCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters ); return scrollCustomQuery( getNativeSQLQueryPlan( spec ).getCustomQuery(), queryParameters );
@ -221,6 +229,11 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
this.tenantIdentifier = identifier; this.tenantIdentifier = identifier;
} }
@Override
public EntityKey generateEntityKey(Serializable id, EntityPersister persister) {
return new EntityKey( id, persister, getEntityMode(), getTenantIdentifier() );
}
private transient JdbcConnectionAccess jdbcConnectionAccess; private transient JdbcConnectionAccess jdbcConnectionAccess;
@Override @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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * 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.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.ConnectionReleaseMode; import org.hibernate.ConnectionReleaseMode;
import org.hibernate.Criteria; import org.hibernate.Criteria;
@ -72,7 +77,6 @@ import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/** /**
* @author Gavin King * @author Gavin King
@ -272,7 +276,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
errorIfClosed(); errorIfClosed();
EntityPersister persister = getFactory().getEntityPersister( entityName ); EntityPersister persister = getFactory().getEntityPersister( entityName );
// first, try to load it from the temp PC associated to this SS // 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 ) { if ( loaded != null ) {
// we found it in the temp PC. Should indicate we are in the midst of processing a result set // 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 // containing eager fetches via join fetch

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -22,10 +22,12 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.type; package org.hibernate.type;
import java.io.Serializable; import java.io.Serializable;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.engine.EntityKey; import org.hibernate.engine.EntityKey;
@ -66,23 +68,15 @@ public class OneToOneType extends EntityType {
} }
public boolean isNull(Object owner, SessionImplementor session) { public boolean isNull(Object owner, SessionImplementor session) {
if ( propertyName != null ) { if ( propertyName != null ) {
final EntityPersister ownerPersister = session.getFactory().getEntityPersister( entityName );
EntityPersister ownerPersister = session.getFactory() final Serializable id = session.getContextEntityIdentifier( owner );
.getEntityPersister(entityName); final EntityKey entityKey = session.generateEntityKey( id, ownerPersister );
Serializable id = session.getContextEntityIdentifier(owner); return session.getPersistenceContext().isPropertyNull( entityKey, getPropertyName() );
EntityKey entityKey = new EntityKey( id, ownerPersister, session.getEntityMode() );
return session.getPersistenceContext()
.isPropertyNull( entityKey, getPropertyName() );
} }
else { else {
return false; return false;
} }
} }
public int getColumnSpan(Mapping session) throws MappingException { 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; package org.hibernate.test.legacy;
import java.io.Serializable; import java.io.Serializable;
@ -335,7 +334,7 @@ public class CustomPersister implements EntityPersister {
if (obj!=null) { if (obj!=null) {
clone = (Custom) obj.clone(); clone = (Custom) obj.clone();
TwoPhaseLoad.addUninitializedEntity( TwoPhaseLoad.addUninitializedEntity(
new EntityKey( id, this, session.getEntityMode() ), session.generateEntityKey( id, this ),
clone, clone,
this, this,
LockMode.NONE, LockMode.NONE,

View File

@ -25,7 +25,6 @@ package org.hibernate.test.multitenancy.schema;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Map;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.MultiTenancyStrategy; import org.hibernate.MultiTenancyStrategy;
@ -33,7 +32,6 @@ import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.internal.BasicServiceRegistryImpl; import org.hibernate.service.internal.BasicServiceRegistryImpl;
import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl; import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; import org.hibernate.service.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
@ -49,7 +47,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.hibernate.testing.env.ConnectionProviderBuilder; import org.hibernate.testing.env.ConnectionProviderBuilder;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
/** /**

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * 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.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.EntityMode; import org.hibernate.EntityMode;
import org.hibernate.FlushMode; import org.hibernate.FlushMode;
@ -44,7 +45,6 @@ import org.hibernate.engine.PersistenceContext;
import org.hibernate.engine.QueryParameters; import org.hibernate.engine.QueryParameters;
import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.transaction.spi.TransactionCoordinator; import org.hibernate.engine.transaction.spi.TransactionCoordinator;
@ -73,11 +73,21 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple
// Delegate methods // Delegate methods
@Override
public String getTenantIdentifier() {
return delegate.getTenantIdentifier();
}
@Override @Override
public JdbcConnectionAccess getJdbcConnectionAccess() { public JdbcConnectionAccess getJdbcConnectionAccess() {
return delegate.getJdbcConnectionAccess(); return delegate.getJdbcConnectionAccess();
} }
@Override
public EntityKey generateEntityKey(Serializable id, EntityPersister persister) {
return delegate.generateEntityKey( id, persister );
}
@Override @Override
public <T> T execute(Callback<T> callback) { public <T> T execute(Callback<T> callback) {
return delegate.execute( callback ); return delegate.execute( callback );