HHH-6330 - Remove entity mode switching capability

This commit is contained in:
Steve Ebersole 2011-06-19 22:12:17 -05:00
parent a8ee266174
commit 4a4f636caf
254 changed files with 2195 additions and 5209 deletions

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate;
@ -30,10 +29,11 @@ package org.hibernate;
* @author Steve Ebersole
*/
public enum EntityMode {
POJO("pojo"),
DOM4J("dom4j"),
MAP("dynamic-map");
POJO( "pojo" ),
MAP( "dynamic-map" );
private final String name;
EntityMode(String name) {
this.name = name;
}
@ -43,12 +43,22 @@ public enum EntityMode {
return name;
}
private static final String DYNAMIC_MAP_NAME = MAP.name.toUpperCase();
/**
* Legacy-style entity-mode name parsing. <b>Case insensitive</b>
*
* @param entityMode The entity mode name to evaluate
*
* @return The appropriate entity mode; {@code null} for incoming {@code entityMode} param is treated by returning
* {@link #POJO}.
*/
public static EntityMode parse(String entityMode) {
if(entityMode == null){
if ( entityMode == null ) {
return POJO;
}
entityMode = entityMode.toUpperCase();
if ( entityMode.equals( "DYNAMIC-MAP" ) ) {
if ( DYNAMIC_MAP_NAME.equals( entityMode ) ) {
return MAP;
}
return valueOf( entityMode );

View File

@ -97,26 +97,6 @@ public interface Session extends SharedSessionContract {
*/
public SharedSessionBuilder sessionWithOptions();
/**
* Retrieve the entity mode in effect for this session.
*
* @return The entity mode for this session.
*/
public EntityMode getEntityMode();
/**
* Starts a new Session with the given entity mode in effect. This secondary
* Session inherits the connection, transaction, and other context
* information from the primary Session. It doesn't need to be flushed
* or closed by the developer.
*
* @param entityMode The entity mode to use for the new session.
* @return The new session
* @deprecated
*/
@Deprecated
public Session getSession(EntityMode entityMode);
/**
* Force this session to flush. Must be called at the end of a
* unit of work, before committing the transaction and closing the

View File

@ -78,15 +78,6 @@ public interface SessionBuilder {
*/
public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
/**
* Use a specific entity mode for these session options
*
* @param entityMode The entity mode to use.
*
* @return {@code this}, for method chaining
*/
public SessionBuilder entityMode(EntityMode entityMode);
/**
* Should the session built automatically join in any ongoing JTA transactions
*

View File

@ -52,13 +52,6 @@ public interface SharedSessionBuilder extends SessionBuilder {
*/
public SharedSessionBuilder connectionReleaseMode();
/**
* Signifies that the entity mode from the original session should be used to create the new session
*
* @return {@code this}, for method chaining
*/
public SharedSessionBuilder entityMode();
/**
* Signifies that the autoJoinTransaction flag from the original session should be used to create the new session
*
@ -99,9 +92,6 @@ public interface SharedSessionBuilder extends SessionBuilder {
@Override
SharedSessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
@Override
SharedSessionBuilder entityMode(EntityMode entityMode);
@Override
SharedSessionBuilder autoJoinTransactions(boolean autoJoinTransactions);

View File

@ -170,7 +170,7 @@ public abstract class CollectionAction implements Executable, Serializable, Comp
else {
//then by fk
return persister.getKeyType()
.compare( key, action.key, session.getEntityMode() );
.compare( key, action.key );
}
}

View File

@ -168,7 +168,7 @@ public abstract class EntityAction
}
else {
//then by id
return persister.getIdentifierType().compare( id, action.id, session.getEntityMode() );
return persister.getIdentifierType().compare( id, action.id );
}
}

View File

@ -75,7 +75,7 @@ public final class EntityDeleteAction extends EntityAction {
// we need to grab the version value from the entity, otherwise
// we have issues with generated-version entities that may have
// multiple actions queued during the same flush
version = persister.getVersion( instance, session.getEntityMode() );
version = persister.getVersion( instance );
}
final CacheKey ck;

View File

@ -104,7 +104,7 @@ public final class EntityInsertAction extends EntityAction {
CacheEntry ce = new CacheEntry(
state,
persister,
persister.hasUninitializedLazyProperties( instance, session.getEntityMode() ),
persister.hasUninitializedLazyProperties( instance ),
version,
session,
instance

View File

@ -93,7 +93,7 @@ public final class EntityUpdateAction extends EntityAction {
// we need to grab the version value from the entity, otherwise
// we have issues with generated-version entities that may have
// multiple actions queued during the same flush
previousVersion = persister.getVersion( instance, session.getEntityMode() );
previousVersion = persister.getVersion( instance );
}
final CacheKey ck;
@ -161,7 +161,7 @@ public final class EntityUpdateAction extends EntityAction {
CacheEntry ce = new CacheEntry(
state,
persister,
persister.hasUninitializedLazyProperties( instance, session.getEntityMode() ),
persister.hasUninitializedLazyProperties( instance ),
nextVersion,
getSession(),
instance

View File

@ -25,7 +25,6 @@ package org.hibernate.cache.spi;
import java.io.Serializable;
import org.hibernate.EntityMode;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.compare.EqualsHelper;
import org.hibernate.type.Type;
@ -41,7 +40,6 @@ public class CacheKey implements Serializable {
private final Serializable key;
private final Type type;
private final String entityOrRoleName;
private final EntityMode entityMode;
private final String tenantId;
private final int hashCode;
@ -53,7 +51,6 @@ public class CacheKey implements Serializable {
* @param id The identifier associated with the cached data
* @param type The Hibernate type mapping
* @param entityOrRoleName The entity or collection-role name.
* @param entityMode The entity mode of the originating session
* @param tenantId The tenant identifier associated this data.
* @param factory The session factory for which we are caching
*/
@ -61,15 +58,13 @@ public class CacheKey implements Serializable {
final Serializable id,
final Type type,
final String entityOrRoleName,
final EntityMode entityMode,
final String tenantId,
final SessionFactoryImplementor factory) {
this.key = id;
this.type = type;
this.entityOrRoleName = entityOrRoleName;
this.entityMode = entityMode;
this.tenantId = tenantId;
this.hashCode = type.getHashCode( key, entityMode, factory );
this.hashCode = type.getHashCode( key, factory );
}
@Override
@ -85,7 +80,7 @@ public class CacheKey implements Serializable {
}
CacheKey that = (CacheKey) other;
return entityOrRoleName.equals( that.entityOrRoleName ) &&
type.isEqual( key, that.key, entityMode ) &&
type.isEqual( key, that.key ) &&
EqualsHelper.equals( tenantId, that.tenantId );
}

View File

@ -26,11 +26,10 @@ package org.hibernate.cache.spi;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.hibernate.EntityMode;
import org.hibernate.Filter;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.FilterImpl;
import org.hibernate.type.Type;
@ -42,15 +41,13 @@ import org.hibernate.type.Type;
*/
public final class FilterKey implements Serializable {
private String filterName;
private Map filterParameters = new HashMap();
private Map<String,TypedValue> filterParameters = new HashMap<String,TypedValue>();
public FilterKey(String name, Map params, Map types, EntityMode entityMode) {
public FilterKey(String name, Map<String,?> params, Map<String,Type> types) {
filterName = name;
Iterator iter = params.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
Type type = (Type) types.get( me.getKey() );
filterParameters.put( me.getKey(), new TypedValue( type, me.getValue(), entityMode ) );
for ( Map.Entry<String, ?> paramEntry : params.entrySet() ) {
Type type = types.get( paramEntry.getKey() );
filterParameters.put( paramEntry.getKey(), new TypedValue( type, paramEntry.getValue() ) );
}
}
@ -73,19 +70,18 @@ public final class FilterKey implements Serializable {
return "FilterKey[" + filterName + filterParameters + ']';
}
public static Set createFilterKeys(Map enabledFilters, EntityMode entityMode) {
if ( enabledFilters.size()==0 ) return null;
Set result = new HashSet();
Iterator iter = enabledFilters.values().iterator();
while ( iter.hasNext() ) {
FilterImpl filter = (FilterImpl) iter.next();
public static Set<FilterKey> createFilterKeys(Map<String,Filter> enabledFilters) {
if ( enabledFilters.size()==0 ) {
return null;
}
Set<FilterKey> result = new HashSet<FilterKey>();
for ( Filter filter : enabledFilters.values() ) {
FilterKey key = new FilterKey(
filter.getName(),
filter.getParameters(),
filter.getFilterDefinition().getParameterTypes(),
entityMode
);
result.add(key);
filter.getName(),
( (FilterImpl) filter ).getParameters(),
filter.getFilterDefinition().getParameterTypes()
);
result.add( key );
}
return result;
}

View File

@ -25,11 +25,9 @@ package org.hibernate.cache.spi;
import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.hibernate.EntityMode;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SessionImplementor;
@ -53,7 +51,6 @@ public class QueryKey implements Serializable {
private final Map namedParameters;
private final Integer firstRow;
private final Integer maxRows;
private final EntityMode entityMode;
private final String tenantIdentifier;
private final Set filterKeys;
@ -95,22 +92,22 @@ public class QueryKey implements Serializable {
}
// disassemble named parameters
final Map namedParameters;
final Map<String,TypedValue> namedParameters;
if ( queryParameters.getNamedParameters() == null ) {
namedParameters = null;
}
else {
namedParameters = CollectionHelper.mapOfSize( queryParameters.getNamedParameters().size() );
Iterator itr = queryParameters.getNamedParameters().entrySet().iterator();
while ( itr.hasNext() ) {
final Map.Entry namedParameterEntry = ( Map.Entry ) itr.next();
final TypedValue original = ( TypedValue ) namedParameterEntry.getValue();
for ( Map.Entry<String,TypedValue> namedParameterEntry : queryParameters.getNamedParameters().entrySet() ) {
namedParameters.put(
namedParameterEntry.getKey(),
new TypedValue(
original.getType(),
original.getType().disassemble( original.getValue(), session, null ),
session.getEntityMode()
namedParameterEntry.getValue().getType(),
namedParameterEntry.getValue().getType().disassemble(
namedParameterEntry.getValue().getValue(),
session,
null
)
)
);
}
@ -137,7 +134,6 @@ public class QueryKey implements Serializable {
firstRow,
maxRows,
filterKeys,
session.getEntityMode(),
session.getTenantIdentifier(),
customTransformer
);
@ -153,8 +149,8 @@ public class QueryKey implements Serializable {
* @param firstRow First row selection, if any.
* @param maxRows Max-rows selection, if any.
* @param filterKeys Enabled filter keys, if any.
* @param entityMode The entity mode.
* @param customTransformer Custom result transformer, if one.
* @param tenantIdentifier The tenant identifier in effect for this query, or {@code null}
*/
QueryKey(
String sqlQueryString,
@ -164,7 +160,6 @@ public class QueryKey implements Serializable {
Integer firstRow,
Integer maxRows,
Set filterKeys,
EntityMode entityMode,
String tenantIdentifier,
CacheableResultTransformer customTransformer) {
this.sqlQueryString = sqlQueryString;
@ -173,7 +168,6 @@ public class QueryKey implements Serializable {
this.namedParameters = namedParameters;
this.firstRow = firstRow;
this.maxRows = maxRows;
this.entityMode = entityMode;
this.tenantIdentifier = tenantIdentifier;
this.filterKeys = filterKeys;
this.customTransformer = customTransformer;
@ -202,7 +196,7 @@ public class QueryKey implements Serializable {
result = 37 * result + ( firstRow==null ? 0 : firstRow.hashCode() );
result = 37 * result + ( maxRows==null ? 0 : maxRows.hashCode() );
for ( int i=0; i< positionalParameterValues.length; i++ ) {
result = 37 * result + ( positionalParameterValues[i]==null ? 0 : positionalParameterTypes[i].getHashCode( positionalParameterValues[i], entityMode ) );
result = 37 * result + ( positionalParameterValues[i]==null ? 0 : positionalParameterTypes[i].getHashCode( positionalParameterValues[i] ) );
}
result = 37 * result + ( namedParameters==null ? 0 : namedParameters.hashCode() );
result = 37 * result + ( filterKeys ==null ? 0 : filterKeys.hashCode() );
@ -246,7 +240,7 @@ public class QueryKey implements Serializable {
if ( positionalParameterTypes[i].getReturnedClass() != that.positionalParameterTypes[i].getReturnedClass() ) {
return false;
}
if ( !positionalParameterTypes[i].isEqual( positionalParameterValues[i], that.positionalParameterValues[i], entityMode ) ) {
if ( !positionalParameterTypes[i].isEqual( positionalParameterValues[i], that.positionalParameterValues[i] ) ) {
return false;
}
}
@ -254,7 +248,6 @@ public class QueryKey implements Serializable {
return EqualsHelper.equals( filterKeys, that.filterKeys )
&& EqualsHelper.equals( namedParameters, that.namedParameters )
&& EqualsHelper.equals( entityMode, that.entityMode )
&& EqualsHelper.equals( tenantIdentifier, that.tenantIdentifier );
}
@ -271,31 +264,29 @@ public class QueryKey implements Serializable {
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer()
.append( "sql: " )
.append( sqlQueryString );
StringBuilder buffer = new StringBuilder( "sql: " ).append( sqlQueryString );
if ( positionalParameterValues != null ) {
buf.append( "; parameters: " );
for ( int i = 0; i < positionalParameterValues.length; i++ ) {
buf.append( positionalParameterValues[i] ).append( ", " );
buffer.append( "; parameters: " );
for ( Object positionalParameterValue : positionalParameterValues ) {
buffer.append( positionalParameterValue ).append( ", " );
}
}
if ( namedParameters != null ) {
buf.append( "; named parameters: " ).append( namedParameters );
buffer.append( "; named parameters: " ).append( namedParameters );
}
if ( filterKeys != null ) {
buf.append( "; filterKeys: " ).append( filterKeys );
buffer.append( "; filterKeys: " ).append( filterKeys );
}
if ( firstRow != null ) {
buf.append( "; first row: " ).append( firstRow );
buffer.append( "; first row: " ).append( firstRow );
}
if ( maxRows != null ) {
buf.append( "; max rows: " ).append( maxRows );
buffer.append( "; max rows: " ).append( maxRows );
}
if ( customTransformer != null ) {
buf.append( "; transformer: " ).append( customTransformer );
buffer.append( "; transformer: " ).append( customTransformer );
}
return buf.toString();
return buffer.toString();
}
}

View File

@ -141,11 +141,7 @@ public final class CacheEntry implements Serializable {
listener.onPreLoad( preLoadEvent );
}
persister.setPropertyValues(
result,
assembledProps,
session.getEntityMode()
);
persister.setPropertyValues( result, assembledProps );
return assembledProps;
}
@ -158,8 +154,7 @@ public final class CacheEntry implements Serializable {
}
public String toString() {
return "CacheEntry(" + subclass + ')' +
ArrayHelper.toString(disassembledState);
return "CacheEntry(" + subclass + ')' + ArrayHelper.toString(disassembledState);
}
}

View File

@ -608,10 +608,10 @@ public final class HbmBinder {
if (nodeName==null) nodeName = StringHelper.unqualify( entity.getEntityName() );
entity.setNodeName(nodeName);
Element tuplizer = locateTuplizerDefinition( node, EntityMode.DOM4J );
if ( tuplizer != null ) {
entity.addTuplizer( EntityMode.DOM4J, tuplizer.attributeValue( "class" ) );
}
// Element tuplizer = locateTuplizerDefinition( node, EntityMode.DOM4J );
// if ( tuplizer != null ) {
// entity.addTuplizer( EntityMode.DOM4J, tuplizer.attributeValue( "class" ) );
// }
}
private static void bindMapRepresentation(Element node, PersistentClass entity,

View File

@ -91,7 +91,7 @@ public class BeanValidationEventListener
public boolean onPreInsert(PreInsertEvent event) {
validate(
event.getEntity(), event.getSession().getEntityMode(), event.getPersister(),
event.getEntity(), event.getPersister().getEntityMode(), event.getPersister(),
event.getSession().getFactory(), GroupsPerOperation.Operation.INSERT
);
return false;
@ -99,7 +99,7 @@ public class BeanValidationEventListener
public boolean onPreUpdate(PreUpdateEvent event) {
validate(
event.getEntity(), event.getSession().getEntityMode(), event.getPersister(),
event.getEntity(), event.getPersister().getEntityMode(), event.getPersister(),
event.getSession().getFactory(), GroupsPerOperation.Operation.UPDATE
);
return false;
@ -107,7 +107,7 @@ public class BeanValidationEventListener
public boolean onPreDelete(PreDeleteEvent event) {
validate(
event.getEntity(), event.getSession().getEntityMode(), event.getPersister(),
event.getEntity(), event.getPersister().getEntityMode(), event.getPersister(),
event.getSession().getFactory(), GroupsPerOperation.Operation.DELETE
);
return false;

View File

@ -46,6 +46,7 @@ import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.collections.EmptyIterator;
import org.hibernate.internal.util.collections.IdentitySet;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type;
@ -58,7 +59,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
private transient SessionImplementor session;
private boolean initialized;
private transient List operationQueue;
private transient List<DelayedOperation> operationQueue;
private transient boolean directlyAccessible;
private transient boolean initializing;
private Object owner;
@ -110,9 +111,11 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
protected final void read() {
initialize(false);
}
/**
* Called by the <tt>size()</tt> method
* Called by the {@link Collection#size} method
*/
@SuppressWarnings( {"JavaDoc"})
protected boolean readSize() {
if (!initialized) {
if ( cachedSize!=-1 && !hasQueuedOperations() ) {
@ -192,10 +195,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return cachedSize;
}
/**
* Is the collection currently connected to an open session?
*/
private final boolean isConnectedToSession() {
private boolean isConnectedToSession() {
return session!=null &&
session.isOpen() &&
session.getPersistenceContext().containsCollection(this);
@ -208,10 +208,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
initialize(true);
dirty();
}
/**
* Is this collection in a state that would allow us to
* "queue" operations?
*/
@SuppressWarnings( {"JavaDoc"})
protected boolean isOperationQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
@ -222,6 +224,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* "queue" puts? This is a special case, because of orphan
* delete.
*/
@SuppressWarnings( {"JavaDoc"})
protected boolean isPutQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
@ -232,6 +235,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* "queue" clear? This is a special case, because of orphan
* delete.
*/
@SuppressWarnings( {"JavaDoc"})
protected boolean isClearQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
@ -241,6 +245,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
/**
* Is this the "inverse" end of a bidirectional association?
*/
@SuppressWarnings( {"JavaDoc"})
private boolean isInverseCollection() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null && ce.getLoadedPersister().isInverse();
@ -250,6 +255,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* Is this the "inverse" end of a bidirectional association with
* no orphan delete enabled?
*/
@SuppressWarnings( {"JavaDoc"})
private boolean isInverseCollectionNoOrphanDelete() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null &&
@ -261,6 +267,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* Is this the "inverse" end of a bidirectional one-to-many, or
* of a collection with no orphan delete?
*/
@SuppressWarnings( {"JavaDoc"})
private boolean isInverseOneToManyOrNoOrphanDelete() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null && ce.getLoadedPersister().isInverse() && (
@ -272,9 +279,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
/**
* Queue an addition
*/
protected final void queueOperation(Object element) {
if (operationQueue==null) operationQueue = new ArrayList(10);
operationQueue.add(element);
@SuppressWarnings( {"JavaDoc"})
protected final void queueOperation(DelayedOperation operation) {
if (operationQueue==null) {
operationQueue = new ArrayList<DelayedOperation>(10);
}
operationQueue.add( operation );
dirty = true; //needed so that we remove this collection from the second-level cache
}
@ -283,8 +293,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* add the queued elements to the underlying collection.
*/
protected final void performQueuedOperations() {
for ( int i=0; i<operationQueue.size(); i++ ) {
( (DelayedOperation) operationQueue.get(i) ).operate();
for ( DelayedOperation operation : operationQueue ) {
operation.operate();
}
}
@ -484,6 +494,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
/**
* Get the current snapshot from the session
*/
@SuppressWarnings( {"JavaDoc"})
protected final Serializable getSnapshot() {
return session.getPersistenceContext().getSnapshot(this);
}
@ -513,7 +524,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return new Iterator() {
int i = 0;
public Object next() {
return ( (DelayedOperation) operationQueue.get(i++) ).getAddedInstance();
return operationQueue.get(i++).getAddedInstance();
}
public boolean hasNext() {
return i<operationQueue.size();
@ -530,16 +541,16 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
/**
* Iterate the "queued" additions
*/
@SuppressWarnings( {"unchecked"})
public final Collection getQueuedOrphans(String entityName) {
if ( hasQueuedOperations() ) {
Collection additions = new ArrayList( operationQueue.size() );
Collection removals = new ArrayList( operationQueue.size() );
for ( int i = 0; i < operationQueue.size(); i++ ) {
DelayedOperation op = (DelayedOperation) operationQueue.get(i);
additions.add( op.getAddedInstance() );
removals.add( op.getOrphan() );
for ( DelayedOperation operation : operationQueue ) {
additions.add( operation.getAddedInstance() );
removals.add( operation.getOrphan() );
}
return getOrphans(removals, additions, entityName, session);
return getOrphans( removals, additions, entityName, session );
}
else {
return CollectionHelper.EMPTY_COLLECTION;
@ -563,74 +574,78 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
/**
* Get the current session
*/
@SuppressWarnings( {"JavaDoc"})
public final SessionImplementor getSession() {
return session;
}
protected final class IteratorProxy implements Iterator {
protected final Iterator iter;
protected final Iterator itr;
public IteratorProxy(Iterator iter) {
this.iter=iter;
public IteratorProxy(Iterator itr) {
this.itr = itr;
}
public boolean hasNext() {
return iter.hasNext();
return itr.hasNext();
}
public Object next() {
return iter.next();
return itr.next();
}
public void remove() {
write();
iter.remove();
itr.remove();
}
}
protected final class ListIteratorProxy implements ListIterator {
protected final ListIterator iter;
protected final ListIterator itr;
public ListIteratorProxy(ListIterator iter) {
this.iter = iter;
public ListIteratorProxy(ListIterator itr) {
this.itr = itr;
}
@SuppressWarnings( {"unchecked"})
public void add(Object o) {
write();
iter.add(o);
itr.add(o);
}
public boolean hasNext() {
return iter.hasNext();
return itr.hasNext();
}
public boolean hasPrevious() {
return iter.hasPrevious();
return itr.hasPrevious();
}
public Object next() {
return iter.next();
return itr.next();
}
public int nextIndex() {
return iter.nextIndex();
return itr.nextIndex();
}
public Object previous() {
return iter.previous();
return itr.previous();
}
public int previousIndex() {
return iter.previousIndex();
return itr.previousIndex();
}
public void remove() {
write();
iter.remove();
itr.remove();
}
@SuppressWarnings( {"unchecked"})
public void set(Object o) {
write();
iter.set(o);
itr.set(o);
}
}
@ -641,11 +656,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
public SetProxy(Collection set) {
this.set=set;
}
@SuppressWarnings( {"unchecked"})
public boolean add(Object o) {
write();
return set.add(o);
}
@SuppressWarnings( {"unchecked"})
public boolean addAll(Collection c) {
write();
return set.addAll(c);
@ -695,6 +713,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return set.toArray();
}
@SuppressWarnings( {"unchecked"})
public Object[] toArray(Object[] array) {
return set.toArray(array);
}
@ -702,183 +721,148 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
protected final class ListProxy implements java.util.List {
protected final java.util.List list;
protected final List list;
public ListProxy(java.util.List list) {
public ListProxy(List list) {
this.list = list;
}
@Override
@SuppressWarnings( {"unchecked"})
public void add(int index, Object value) {
write();
list.add(index, value);
}
/**
* @see java.util.Collection#add(Object)
*/
@Override
@SuppressWarnings( {"unchecked"})
public boolean add(Object o) {
write();
return list.add(o);
}
/**
* @see java.util.Collection#addAll(Collection)
*/
@Override
@SuppressWarnings( {"unchecked"})
public boolean addAll(Collection c) {
write();
return list.addAll(c);
}
/**
* @see java.util.List#addAll(int, Collection)
*/
@Override
@SuppressWarnings( {"unchecked"})
public boolean addAll(int i, Collection c) {
write();
return list.addAll(i, c);
}
/**
* @see java.util.Collection#clear()
*/
@Override
public void clear() {
write();
list.clear();
}
/**
* @see java.util.Collection#contains(Object)
*/
@Override
public boolean contains(Object o) {
return list.contains(o);
}
/**
* @see java.util.Collection#containsAll(Collection)
*/
@Override
public boolean containsAll(Collection c) {
return list.containsAll(c);
}
/**
* @see java.util.List#get(int)
*/
@Override
public Object get(int i) {
return list.get(i);
}
/**
* @see java.util.List#indexOf(Object)
*/
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
/**
* @see java.util.Collection#isEmpty()
*/
@Override
public boolean isEmpty() {
return list.isEmpty();
}
/**
* @see java.util.Collection#iterator()
*/
@Override
public Iterator iterator() {
return new IteratorProxy( list.iterator() );
}
/**
* @see java.util.List#lastIndexOf(Object)
*/
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
/**
* @see java.util.List#listIterator()
*/
@Override
public ListIterator listIterator() {
return new ListIteratorProxy( list.listIterator() );
}
/**
* @see java.util.List#listIterator(int)
*/
@Override
public ListIterator listIterator(int i) {
return new ListIteratorProxy( list.listIterator(i) );
}
/**
* @see java.util.List#remove(int)
*/
@Override
public Object remove(int i) {
write();
return list.remove(i);
}
/**
* @see java.util.Collection#remove(Object)
*/
@Override
public boolean remove(Object o) {
write();
return list.remove(o);
}
/**
* @see java.util.Collection#removeAll(Collection)
*/
@Override
public boolean removeAll(Collection c) {
write();
return list.removeAll(c);
}
/**
* @see java.util.Collection#retainAll(Collection)
*/
@Override
public boolean retainAll(Collection c) {
write();
return list.retainAll(c);
}
/**
* @see java.util.List#set(int, Object)
*/
@Override
@SuppressWarnings( {"unchecked"})
public Object set(int i, Object o) {
write();
return list.set(i, o);
return list.set( i, o );
}
/**
* @see java.util.Collection#size()
*/
@Override
public int size() {
return list.size();
}
/**
* @see java.util.List#subList(int, int)
*/
@Override
public List subList(int i, int j) {
return list.subList(i, j);
}
/**
* @see java.util.Collection#toArray()
*/
@Override
public Object[] toArray() {
return list.toArray();
}
/**
* @see java.util.Collection#toArray(Object[])
*/
@Override
@SuppressWarnings( {"unchecked"})
public Object[] toArray(Object[] array) {
return list.toArray(array);
}
}
/**
* Contract for operations which are part of a collection's operation queue.
*/
protected interface DelayedOperation {
public void operate();
public Object getAddedInstance();
@ -890,18 +874,23 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
* belong to the collection, and a collection of instances
* that currently belong, return a collection of orphans
*/
@SuppressWarnings( {"JavaDoc", "unchecked"})
protected static Collection getOrphans(
Collection oldElements,
Collection currentElements,
String entityName,
SessionImplementor session)
throws HibernateException {
SessionImplementor session) throws HibernateException {
// short-circuit(s)
if ( currentElements.size()==0 ) return oldElements; // no new elements, the old list contains only Orphans
if ( oldElements.size()==0) return oldElements; // no old elements, so no Orphans neither
Type idType = session.getFactory().getEntityPersister(entityName).getIdentifierType();
if ( currentElements.size()==0 ) {
return oldElements; // no new elements, the old list contains only Orphans
}
if ( oldElements.size()==0) {
return oldElements; // no old elements, so no Orphans neither
}
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
final Type idType = entityPersister.getIdentifierType();
// create the collection holding the Orphans
Collection res = new ArrayList();
@ -909,27 +898,29 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
java.util.Set currentIds = new HashSet();
java.util.Set currentSaving = new IdentitySet();
for ( Iterator it=currentElements.iterator(); it.hasNext(); ) {
Object current = it.next();
if ( current!=null && ForeignKeys.isNotTransient(entityName, current, null, session) ) {
for ( Object current : currentElements ) {
if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
EntityEntry ee = session.getPersistenceContext().getEntry( current );
if ( ee != null && ee.getStatus() == Status.SAVING ) {
currentSaving.add( current );
}
else {
Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, current, session);
currentIds.add( new TypedValue( idType, currentId, session.getEntityMode() ) );
Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
entityName,
current,
session
);
currentIds.add( new TypedValue( idType, currentId, entityPersister.getEntityMode() ) );
}
}
}
// iterate over the *old* list
for ( Iterator it=oldElements.iterator(); it.hasNext(); ) {
Object old = it.next();
if ( ! currentSaving.contains( old ) ) {
for ( Object old : oldElements ) {
if ( !currentSaving.contains( old ) ) {
Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
if ( !currentIds.contains( new TypedValue( idType, oldId, session.getEntityMode() ) ) ) {
res.add(old);
if ( !currentIds.contains( new TypedValue( idType, oldId, entityPersister.getEntityMode() ) ) ) {
res.add( old );
}
}
}
@ -944,15 +935,15 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
SessionImplementor session) throws HibernateException {
if ( object!=null && ForeignKeys.isNotTransient(entityName, object, null, session) ) {
Type idType = session.getFactory().getEntityPersister(entityName).getIdentifierType();
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
Type idType = entityPersister.getIdentifierType();
Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, object, session);
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, iter.next(), session);
if ( idType.isEqual( idOfCurrent, idOfOld, session.getEntityMode(), session.getFactory() ) ) {
iter.remove();
Iterator itr = list.iterator();
while ( itr.hasNext() ) {
Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, itr.next(), session);
if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
itr.remove();
break;
}
}

View File

@ -64,13 +64,12 @@ public class PersistentArrayHolder extends AbstractPersistentCollection {
}
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
int length = /*(array==null) ? tempList.size() :*/ Array.getLength(array);
Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
for ( int i=0; i<length; i++ ) {
Object elt = /*(array==null) ? tempList.get(i) :*/ Array.get(array, i);
try {
Array.set( result, i, persister.getElementType().deepCopy(elt, entityMode, persister.getFactory()) );
Array.set( result, i, persister.getElementType().deepCopy(elt, persister.getFactory()) );
}
catch (IllegalArgumentException iae) {
LOG.invalidArrayElementType(iae.getMessage());

View File

@ -99,15 +99,14 @@ public class PersistentBag extends AbstractPersistentCollection implements List
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
Type elementType = persister.getElementType();
EntityMode entityMode = getSession().getEntityMode();
List sn = (List) getSnapshot();
if ( sn.size()!=bag.size() ) return false;
Iterator iter = bag.iterator();
while ( iter.hasNext() ) {
Object elt = iter.next();
final boolean unequal = countOccurrences(elt, bag, elementType, entityMode) !=
countOccurrences(elt, sn, elementType, entityMode);
if ( unequal ) return false;
for ( Object elt : bag ) {
final boolean unequal = countOccurrences( elt, bag, elementType )
!= countOccurrences( elt, sn, elementType );
if ( unequal ) {
return false;
}
}
return true;
}
@ -116,23 +115,22 @@ public class PersistentBag extends AbstractPersistentCollection implements List
return ( (Collection) snapshot ).isEmpty();
}
private int countOccurrences(Object element, List list, Type elementType, EntityMode entityMode)
private int countOccurrences(Object element, List list, Type elementType)
throws HibernateException {
Iterator iter = list.iterator();
int result=0;
while ( iter.hasNext() ) {
if ( elementType.isSame( element, iter.next(), entityMode ) ) result++;
if ( elementType.isSame( element, iter.next() ) ) result++;
}
return result;
}
public Serializable getSnapshot(CollectionPersister persister)
throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
ArrayList clonedList = new ArrayList( bag.size() );
Iterator iter = bag.iterator();
while ( iter.hasNext() ) {
clonedList.add( persister.getElementType().deepCopy( iter.next(), entityMode, persister.getFactory() ) );
clonedList.add( persister.getElementType().deepCopy( iter.next(), persister.getFactory() ) );
}
return clonedList;
}
@ -183,7 +181,6 @@ public class PersistentBag extends AbstractPersistentCollection implements List
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
//if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
Type elementType = persister.getElementType();
EntityMode entityMode = getSession().getEntityMode();
ArrayList deletes = new ArrayList();
List sn = (List) getSnapshot();
Iterator olditer = sn.iterator();
@ -192,7 +189,7 @@ public class PersistentBag extends AbstractPersistentCollection implements List
Object old = olditer.next();
Iterator newiter = bag.iterator();
boolean found = false;
if ( bag.size()>i && elementType.isSame( old, bag.get(i++), entityMode ) ) {
if ( bag.size()>i && elementType.isSame( old, bag.get(i++) ) ) {
//a shortcut if its location didn't change!
found = true;
}
@ -200,7 +197,7 @@ public class PersistentBag extends AbstractPersistentCollection implements List
//search for it
//note that this code is incorrect for other than one-to-many
while ( newiter.hasNext() ) {
if ( elementType.isSame( old, newiter.next(), entityMode ) ) {
if ( elementType.isSame( old, newiter.next() ) ) {
found = true;
break;
}
@ -214,8 +211,7 @@ public class PersistentBag extends AbstractPersistentCollection implements List
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
//if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
List sn = (List) getSnapshot();
final EntityMode entityMode = getSession().getEntityMode();
if ( sn.size()>i && elemType.isSame( sn.get(i), entry, entityMode ) ) {
if ( sn.size()>i && elemType.isSame( sn.get(i), entry ) ) {
//a shortcut if its location didn't change!
return false;
}
@ -225,7 +221,7 @@ public class PersistentBag extends AbstractPersistentCollection implements List
Iterator olditer = sn.iterator();
while ( olditer.hasNext() ) {
Object old = olditer.next();
if ( elemType.isSame( old, entry, entityMode ) ) return false;
if ( elemType.isSame( old, entry ) ) return false;
}
return true;
}

View File

@ -64,7 +64,7 @@ public class PersistentElementHolder extends AbstractPersistentCollection {
for ( int i=0; i<elements.size(); i++ ) {
Element elem = (Element) elements.get(i);
Object value = elementType.fromXMLNode( elem, persister.getFactory() );
Object copy = elementType.deepCopy(value , getSession().getEntityMode(), persister.getFactory() );
Object copy = elementType.deepCopy(value , persister.getFactory() );
snapshot.add(copy);
}
return snapshot;

View File

@ -295,11 +295,7 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem
return element;
}
public Serializable getSnapshot(CollectionPersister persister)
throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
HashMap map = new HashMap( values.size() );
Iterator iter = values.iterator();
int i=0;
@ -307,7 +303,7 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem
Object value = iter.next();
map.put(
identifiers.get( new Integer(i++) ),
persister.getElementType().deepCopy(value, entityMode, persister.getFactory())
persister.getElementType().deepCopy(value, persister.getFactory())
);
}
return map;

View File

@ -96,7 +96,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
for ( int i=0; i<elements.size(); i++ ) {
Element elem = (Element) elements.get(i);
Object value = elementType.fromXMLNode( elem, persister.getFactory() );
Object copy = elementType.deepCopy( value, getSession().getEntityMode(), persister.getFactory() );
Object copy = elementType.deepCopy( value, persister.getFactory() );
snapshot.put( getIndex(elem, indexNode, i), copy );
}
return snapshot;

View File

@ -47,28 +47,28 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class PersistentList extends AbstractPersistentCollection implements List {
protected List list;
@Override
@SuppressWarnings( {"unchecked"})
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
final EntityMode entityMode = persister.getOwnerEntityPersister().getEntityMode();
ArrayList clonedList = new ArrayList( list.size() );
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
Object deepCopy = persister.getElementType()
.deepCopy( iter.next(), entityMode, persister.getFactory() );
for ( Object element : list ) {
Object deepCopy = persister.getElementType().deepCopy( element, persister.getFactory() );
clonedList.add( deepCopy );
}
return clonedList;
}
@Override
public Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException {
List sn = (List) snapshot;
return getOrphans( sn, list, entityName, getSession() );
}
@Override
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
Type elementType = persister.getElementType();
List sn = (List) getSnapshot();
@ -81,6 +81,7 @@ public class PersistentList extends AbstractPersistentCollection implements List
return true;
}
@Override
public boolean isSnapshotEmpty(Serializable snapshot) {
return ( (Collection) snapshot ).isEmpty();
}

View File

@ -86,14 +86,12 @@ public class PersistentMap extends AbstractPersistentCollection implements Map {
setDirectlyAccessible(true);
}
@SuppressWarnings( {"unchecked"})
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
HashMap clonedMap = new HashMap( map.size() );
Iterator iter = map.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry e = (Map.Entry) iter.next();
final Object copy = persister.getElementType()
.deepCopy( e.getValue(), entityMode, persister.getFactory() );
for ( Object o : map.entrySet() ) {
Entry e = (Entry) o;
final Object copy = persister.getElementType().deepCopy( e.getValue(), persister.getFactory() );
clonedMap.put( e.getKey(), copy );
}
return clonedMap;

View File

@ -92,17 +92,13 @@ public class PersistentSet extends AbstractPersistentCollection implements java.
}
public Serializable getSnapshot(CollectionPersister persister)
throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
//if (set==null) return new Set(session);
@SuppressWarnings( {"unchecked"})
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
HashMap clonedSet = new HashMap( set.size() );
Iterator iter = set.iterator();
while ( iter.hasNext() ) {
for ( Object aSet : set ) {
Object copied = persister.getElementType()
.deepCopy( iter.next(), entityMode, persister.getFactory() );
clonedSet.put(copied, copied);
.deepCopy( aSet, persister.getFactory() );
clonedSet.put( copied, copied );
}
return clonedSet;
}

View File

@ -53,7 +53,7 @@ public class PersistentSortedMap extends PersistentMap implements SortedMap {
Iterator iter = map.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry e = (Map.Entry) iter.next();
clonedMap.put( e.getKey(), persister.getElementType().deepCopy( e.getValue(), entityMode, persister.getFactory() ) );
clonedMap.put( e.getKey(), persister.getElementType().deepCopy( e.getValue(), persister.getFactory() ) );
}
return clonedMap;
}

View File

@ -51,7 +51,7 @@ public class PersistentSortedSet extends PersistentSet implements SortedSet {
TreeMap clonedSet = new TreeMap(comparator);
Iterator iter = set.iterator();
while ( iter.hasNext() ) {
Object copy = persister.getElementType().deepCopy( iter.next(), entityMode, persister.getFactory() );
Object copy = persister.getElementType().deepCopy( iter.next(), persister.getFactory() );
clonedSet.put(copy, copy);
}
return clonedSet;

View File

@ -203,7 +203,7 @@ public class Example implements Criterion {
String[] propertyNames = meta.getPropertyNames();
Type[] propertyTypes = meta.getPropertyTypes();
//TODO: get all properties, not just the fetched ones!
Object[] propertyValues = meta.getPropertyValues( entity, getEntityMode(criteria, criteriaQuery) );
Object[] propertyValues = meta.getPropertyValues( entity );
for (int i=0; i<propertyNames.length; i++) {
Object propertyValue = propertyValues[i];
String propertyName = propertyNames[i];
@ -246,7 +246,7 @@ public class Example implements Criterion {
String[] propertyNames = meta.getPropertyNames();
Type[] propertyTypes = meta.getPropertyTypes();
//TODO: get all properties, not just the fetched ones!
Object[] values = meta.getPropertyValues( entity, getEntityMode(criteria, criteriaQuery) );
Object[] values = meta.getPropertyValues( entity );
List list = new ArrayList();
for (int i=0; i<propertyNames.length; i++) {
Object value = values[i];
@ -271,8 +271,8 @@ public class Example implements Criterion {
private EntityMode getEntityMode(Criteria criteria, CriteriaQuery criteriaQuery) {
EntityPersister meta = criteriaQuery.getFactory()
.getEntityPersister( criteriaQuery.getEntityName(criteria) );
EntityMode result = meta.guessEntityMode(entity);
if (result==null) {
EntityMode result = meta.getEntityMode();
if ( ! meta.getEntityMetamodel().getTuplizer().isInstance( entity ) ) {
throw new ClassCastException( entity.getClass().getName() );
}
return result;

View File

@ -31,7 +31,6 @@ import java.util.Stack;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CascadeStyle;
@ -151,8 +150,7 @@ public final class Cascade {
Type[] types = persister.getPropertyTypes();
CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles();
EntityMode entityMode = eventSource.getEntityMode();
boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent, entityMode );
boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent );
for ( int i=0; i<types.length; i++) {
final CascadeStyle style = cascadeStyles[i];
final String propertyName = persister.getPropertyNames()[i];
@ -164,7 +162,7 @@ public final class Cascade {
if ( style.doCascade( action ) ) {
cascadeProperty(
parent,
persister.getPropertyValue( parent, i, entityMode ),
persister.getPropertyValue( parent, i ),
types[i],
style,
propertyName,
@ -175,7 +173,7 @@ public final class Cascade {
else if ( action.requiresNoCascadeChecking() ) {
action.noCascade(
eventSource,
persister.getPropertyValue( parent, i, entityMode ),
persister.getPropertyValue( parent, i ),
parent,
persister,
i
@ -277,26 +275,10 @@ public final class Cascade {
return type.isEntityType() && ( (EntityType) type ).isLogicalOneToOne();
}
private String composePropertyPath(String propertyName) {
if ( componentPathStack.isEmpty() ) {
return propertyName;
}
else {
StringBuffer buffer = new StringBuffer();
Iterator itr = componentPathStack.iterator();
while ( itr.hasNext() ) {
buffer.append( itr.next() ).append( '.' );
}
buffer.append( propertyName );
return buffer.toString();
}
}
private Stack componentPathStack = new Stack();
private boolean cascadeAssociationNow(AssociationType associationType) {
return associationType.getForeignKeyDirection().cascadeNow(cascadeTo) &&
( eventSource.getEntityMode()!=EntityMode.DOM4J || associationType.isEmbeddedInXML() );
return associationType.getForeignKeyDirection().cascadeNow(cascadeTo);
}
private void cascadeComponent(
@ -410,12 +392,8 @@ public final class Cascade {
final Type elemType,
final Object anything,
final boolean isCascadeDeleteEnabled) throws HibernateException {
// we can't cascade to non-embedded elements
boolean embeddedElements = eventSource.getEntityMode()!=EntityMode.DOM4J ||
( (EntityType) collectionType.getElementType( eventSource.getFactory() ) ).isEmbeddedInXML();
boolean reallyDoCascade = style.reallyDoCascade(action) &&
embeddedElements && child!=CollectionType.UNFETCHED_COLLECTION;
boolean reallyDoCascade = style.reallyDoCascade(action) && child!=CollectionType.UNFETCHED_COLLECTION;
if ( reallyDoCascade ) {
LOG.trace("Cascade " + action + " for collection: " + collectionType.getRole());

View File

@ -28,7 +28,6 @@ import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionEntry;
@ -42,50 +41,52 @@ import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType;
import org.hibernate.type.Type;
/**
* Implements book-keeping for the collection persistence by reachability algorithm
*
* @author Gavin King
*/
public final class Collections {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Collections.class.getName());
private Collections() {}
private Collections() {
}
/**
* record the fact that this collection was dereferenced
*
* @param coll The collection to be updated by unreachability.
* @throws HibernateException
* @param coll The collection to be updated by un-reachability.
*/
public static void processUnreachableCollection(PersistentCollection coll, SessionImplementor session)
throws HibernateException {
@SuppressWarnings( {"JavaDoc"})
public static void processUnreachableCollection(PersistentCollection coll, SessionImplementor session) {
if ( coll.getOwner()==null ) {
processNeverReferencedCollection(coll, session);
}
else {
processDereferencedCollection(coll, session);
}
}
private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session)
throws HibernateException {
private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session) {
final PersistenceContext persistenceContext = session.getPersistenceContext();
CollectionEntry entry = persistenceContext.getCollectionEntry(coll);
final CollectionPersister loadedPersister = entry.getLoadedPersister();
if (LOG.isDebugEnabled() && loadedPersister != null) LOG.debugf("Collection dereferenced: %s",
MessageHelper.collectionInfoString(loadedPersister,
entry.getLoadedKey(),
session.getFactory()));
if (LOG.isDebugEnabled() && loadedPersister != null) {
LOG.debugf(
"Collection dereferenced: %s",
MessageHelper.collectionInfoString(
loadedPersister,
entry.getLoadedKey(),
session.getFactory()
)
);
}
// do a check
boolean hasOrphanDelete = loadedPersister != null &&
loadedPersister.hasOrphanDelete();
boolean hasOrphanDelete = loadedPersister != null && loadedPersister.hasOrphanDelete();
if (hasOrphanDelete) {
Serializable ownerId = loadedPersister.getOwnerEntityPersister().getIdentifier( coll.getOwner(), session );
if ( ownerId == null ) {
@ -123,7 +124,7 @@ public final class Collections {
// do the work
entry.setCurrentPersister(null);
entry.setCurrentKey(null);
prepareCollectionForUpdate( coll, entry, session.getEntityMode(), session.getFactory() );
prepareCollectionForUpdate( coll, entry, session.getFactory() );
}
@ -139,7 +140,7 @@ public final class Collections {
entry.setCurrentPersister( entry.getLoadedPersister() );
entry.setCurrentKey( entry.getLoadedKey() );
prepareCollectionForUpdate( coll, entry, session.getEntityMode(), session.getFactory() );
prepareCollectionForUpdate( coll, entry, session.getFactory() );
}
@ -149,14 +150,13 @@ public final class Collections {
* @param collection The collection to be updated by reachability.
* @param type The type of the collection.
* @param entity The owner of the collection.
* @throws HibernateException
* @param session The session from which this request originates
*/
public static void processReachableCollection(
PersistentCollection collection,
CollectionType type,
Object entity,
SessionImplementor session)
throws HibernateException {
SessionImplementor session) {
collection.setOwner(entity);
@ -197,7 +197,7 @@ public final class Collections {
MessageHelper.collectionInfoString(ce.getLoadedPersister(), ce.getLoadedKey(), factory));
}
prepareCollectionForUpdate( collection, ce, session.getEntityMode(), factory );
prepareCollectionForUpdate( collection, ce, factory );
}
@ -206,17 +206,16 @@ public final class Collections {
* 2. decide if the collection needs deleting/creating/updating (but
* don't actually schedule the action yet)
*/
@SuppressWarnings( {"JavaDoc"})
private static void prepareCollectionForUpdate(
PersistentCollection collection,
CollectionEntry entry,
EntityMode entityMode,
SessionFactoryImplementor factory)
throws HibernateException {
SessionFactoryImplementor factory) {
if ( entry.isProcessed() ) {
throw new AssertionFailure( "collection was processed twice by flush()" );
}
entry.setProcessed(true);
entry.setProcessed( true );
final CollectionPersister loadedPersister = entry.getLoadedPersister();
final CollectionPersister currentPersister = entry.getCurrentPersister();
@ -227,7 +226,7 @@ public final class Collections {
.getKeyType().isEqual( // or its key changed
entry.getLoadedKey(),
entry.getCurrentKey(),
entityMode, factory
factory
);
if (ownerChanged) {
@ -241,25 +240,25 @@ public final class Collections {
throw new HibernateException(
"Don't change the reference to a collection with cascade=\"all-delete-orphan\": " +
loadedPersister.getRole()
);
);
}
// do the work
if ( currentPersister != null ) {
entry.setDorecreate(true); // we will need to create new entries
entry.setDorecreate( true ); // we will need to create new entries
}
if ( loadedPersister != null ) {
entry.setDoremove(true); // we will need to remove ye olde entries
entry.setDoremove( true ); // we will need to remove ye olde entries
if ( entry.isDorecreate() ) {
LOG.trace("Forcing collection initialization");
collection.forceInitialization(); // force initialize!
LOG.trace( "Forcing collection initialization" );
collection.forceInitialization();
}
}
}
else if ( collection.isDirty() ) { // else if it's elements changed
entry.setDoupdate(true);
else if ( collection.isDirty() ) {
// the collection's elements have changed
entry.setDoupdate( true );
}
}

View File

@ -25,6 +25,7 @@ package org.hibernate.engine.internal;
import java.io.Serializable;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.TransientObjectException;
import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
@ -108,7 +109,10 @@ public final class ForeignKeys {
subvalues[i] = replacement;
}
}
if (substitute) actype.setPropertyValues( value, subvalues, session.getEntityMode() );
if ( substitute ) {
// todo : need to account for entity mode on the CompositeType interface :(
actype.setPropertyValues( value, subvalues, EntityMode.POJO );
}
return value;
}
else {

View File

@ -25,6 +25,7 @@ package org.hibernate.engine.internal;
import java.util.Iterator;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.PropertyValueException;
import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
@ -54,7 +55,7 @@ public final class Nullability {
*
* @param values entity properties
* @param persister class persister
* @param isUpdate wether it is intended to be updated or saved
* @param isUpdate whether it is intended to be updated or saved
* @throws org.hibernate.PropertyValueException Break the nullability of one property
* @throws HibernateException error while getting Component values
*/
@ -180,7 +181,7 @@ public final class Nullability {
boolean[] nullability = compType.getPropertyNullability();
if ( nullability!=null ) {
//do the test
final Object[] values = compType.getPropertyValues( value, session.getEntityMode() );
final Object[] values = compType.getPropertyValues( value, EntityMode.POJO );
final Type[] propertyTypes = compType.getSubtypes();
for ( int i=0; i<values.length; i++ ) {
final Object subvalue = values[i];

View File

@ -130,7 +130,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// A container for collections we load up when the owning entity is not
// yet loaded ... for now, this is purely transient!
private Map unownedCollections;
private Map<CollectionKey,PersistentCollection> unownedCollections;
// Parent entities cache by their child for cascading
// May be empty or not contains all relation
@ -194,17 +194,17 @@ public class StatefulPersistenceContext implements PersistenceContext {
public void addUnownedCollection(CollectionKey key, PersistentCollection collection) {
if (unownedCollections==null) {
unownedCollections = new HashMap(8);
unownedCollections = new HashMap<CollectionKey,PersistentCollection>(8);
}
unownedCollections.put(key, collection);
unownedCollections.put( key, collection );
}
public PersistentCollection useUnownedCollection(CollectionKey key) {
if (unownedCollections==null) {
if ( unownedCollections == null ) {
return null;
}
else {
return (PersistentCollection) unownedCollections.remove(key);
return unownedCollections.remove(key);
}
}
@ -220,14 +220,13 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
public void clear() {
Iterator itr = proxiesByKey.values().iterator();
while ( itr.hasNext() ) {
final LazyInitializer li = ( ( HibernateProxy ) itr.next() ).getHibernateLazyInitializer();
for ( Object o : proxiesByKey.values() ) {
final LazyInitializer li = ((HibernateProxy) o).getHibernateLazyInitializer();
li.unsetSession();
}
Map.Entry[] collectionEntryArray = IdentityMap.concurrentEntries( collectionEntries );
for ( int i = 0; i < collectionEntryArray.length; i++ ) {
( ( PersistentCollection ) collectionEntryArray[i].getKey() ).unsetSession( getSession() );
for ( Map.Entry aCollectionEntryArray : collectionEntryArray ) {
((PersistentCollection) aCollectionEntryArray.getKey()).unsetSession( getSession() );
}
arrayHolders.clear();
entitiesByKey.clear();
@ -284,9 +283,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
public void afterTransactionCompletion() {
cleanUpInsertedKeysAfterTransaction();
// Downgrade locks
Iterator iter = entityEntries.values().iterator();
while ( iter.hasNext() ) {
( (EntityEntry) iter.next() ).setLockMode(LockMode.NONE);
for ( Object o : entityEntries.values() ) {
((EntityEntry) o).setLockMode( LockMode.NONE );
}
}
@ -510,7 +508,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
lockMode,
existsInDatabase,
persister,
session.getEntityMode(),
persister.getEntityMode(),
session.getTenantIdentifier(),
disableVersionIncrement,
lazyPropertiesAreUnfetched
@ -667,13 +665,15 @@ public class StatefulPersistenceContext implements PersistenceContext {
* @throws HibernateException
*/
public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
throws HibernateException {
throws HibernateException {
boolean alreadyNarrow = persister.getConcreteProxyClass( session.getEntityMode() )
.isAssignableFrom( proxy.getClass() );
final Class concreteProxyClass = persister.getConcreteProxyClass();
boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() );
if ( !alreadyNarrow ) {
if (LOG.isEnabled(WARN)) LOG.narrowingProxy(persister.getConcreteProxyClass(session.getEntityMode()));
if ( LOG.isEnabled(WARN) ) {
LOG.narrowingProxy( concreteProxyClass );
}
if ( object != null ) {
proxiesByKey.remove(key);
@ -824,7 +824,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
collectionEntries.put( coll, entry );
CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key, session.getEntityMode() );
CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
PersistentCollection old = ( PersistentCollection ) collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
if ( old == coll ) {
@ -1247,11 +1247,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent) {
Object collection = persister.getPropertyValue(
potentialParent,
property,
session.getEntityMode()
);
Object collection = persister.getPropertyValue( potentialParent, property );
return collection != null
&& Hibernate.isInitialized( collection )
&& collectionPersister.getCollectionType().contains( collection, childEntity, session );
@ -1323,7 +1319,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
CollectionPersister collectionPersister,
Object potentialParent
){
Object collection = persister.getPropertyValue( potentialParent, property, session.getEntityMode() );
Object collection = persister.getPropertyValue( potentialParent, property );
if ( collection!=null && Hibernate.isInitialized(collection) ) {
return collectionPersister.getCollectionType().indexOf(collection, childEntity);
}

View File

@ -165,7 +165,7 @@ public final class TwoPhaseLoad {
}
}
persister.setPropertyValues( entity, hydratedState, session.getEntityMode() );
persister.setPropertyValues( entity, hydratedState );
final SessionFactoryImplementor factory = session.getFactory();
if ( persister.hasCache() && session.getCacheMode().isPutEnabled() ) {

View File

@ -108,7 +108,7 @@ public class CollectionLoadContext {
* @return The loading collection (see discussion above).
*/
public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) {
final EntityMode em = loadContexts.getPersistenceContext().getSession().getEntityMode();
final EntityMode em = persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode();
final CollectionKey collectionKey = new CollectionKey( persister, key, em );
if (LOG.isTraceEnabled()) LOG.trace("Starting attempt to find loading collection ["
+ MessageHelper.collectionInfoString(persister.getRole(), key) + "]");
@ -126,8 +126,7 @@ public class CollectionLoadContext {
else {
Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister );
final boolean newlySavedEntity = owner != null
&& loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING
&& em != EntityMode.DOM4J;
&& loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING;
if ( newlySavedEntity ) {
// important, to account for newly saved entities in query
// todo : some kind of check for new status...
@ -189,7 +188,11 @@ public class CollectionLoadContext {
matches.add( lce );
if ( lce.getCollection().getOwner() == null ) {
session.getPersistenceContext().addUnownedCollection(
new CollectionKey( persister, lce.getKey(), session.getEntityMode() ),
new CollectionKey(
persister,
lce.getKey(),
persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode()
),
lce.getCollection()
);
}
@ -233,11 +236,10 @@ public class CollectionLoadContext {
private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
LOG.trace("Ending loading collection [" + lce + "]");
final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();
final EntityMode em = session.getEntityMode();
boolean hasNoQueuedAdds = lce.getCollection().endRead(); // warning: can cause a recursive calls! (proxy initialization)
if ( persister.getCollectionType().hasHolder( em ) ) {
if ( persister.getCollectionType().hasHolder() ) {
getLoadContext().getPersistenceContext().addCollectionHolder( lce.getCollection() );
}
@ -255,9 +257,15 @@ public class CollectionLoadContext {
!ce.isDoremove(); // and this is not a forced initialization during flush
if (addToCache) addCollectionToCache(lce, persister);
if (LOG.isDebugEnabled()) LOG.debugf("Collection fully initialized: %s",
MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory()));
if (session.getFactory().getStatistics().isStatisticsEnabled()) session.getFactory().getStatisticsImplementor().loadCollection(persister.getRole());
if (LOG.isDebugEnabled()) {
LOG.debugf(
"Collection fully initialized: %s",
MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory())
);
}
if (session.getFactory().getStatistics().isStatisticsEnabled()) {
session.getFactory().getStatisticsImplementor().loadCollection(persister.getRole());
}
}
/**

View File

@ -26,13 +26,11 @@ package org.hibernate.engine.loading.internal;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.PersistenceContext;
@ -63,10 +61,10 @@ public class LoadContexts {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, LoadContexts.class.getName());
private final PersistenceContext persistenceContext;
private Map collectionLoadContexts;
private Map entityLoadContexts;
private Map<ResultSet,CollectionLoadContext> collectionLoadContexts;
private Map<ResultSet,EntityLoadContext> entityLoadContexts;
private Map xrefLoadingCollectionEntries;
private Map<CollectionKey,LoadingCollectionEntry> xrefLoadingCollectionEntries;
/**
* Creates and binds this to the given persistence context.
@ -91,10 +89,6 @@ public class LoadContexts {
return getPersistenceContext().getSession();
}
private EntityMode getEntityMode() {
return getSession().getEntityMode();
}
// cleanup code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -109,11 +103,11 @@ public class LoadContexts {
*/
public void cleanup(ResultSet resultSet) {
if ( collectionLoadContexts != null ) {
CollectionLoadContext collectionLoadContext = ( CollectionLoadContext ) collectionLoadContexts.remove( resultSet );
CollectionLoadContext collectionLoadContext = collectionLoadContexts.remove( resultSet );
collectionLoadContext.cleanup();
}
if ( entityLoadContexts != null ) {
EntityLoadContext entityLoadContext = ( EntityLoadContext ) entityLoadContexts.remove( resultSet );
EntityLoadContext entityLoadContext = entityLoadContexts.remove( resultSet );
entityLoadContext.cleanup();
}
}
@ -126,19 +120,15 @@ public class LoadContexts {
*/
public void cleanup() {
if ( collectionLoadContexts != null ) {
Iterator itr = collectionLoadContexts.values().iterator();
while ( itr.hasNext() ) {
CollectionLoadContext collectionLoadContext = ( CollectionLoadContext ) itr.next();
LOG.failSafeCollectionsCleanup(collectionLoadContext);
for ( CollectionLoadContext collectionLoadContext : collectionLoadContexts.values() ) {
LOG.failSafeCollectionsCleanup( collectionLoadContext );
collectionLoadContext.cleanup();
}
collectionLoadContexts.clear();
}
if ( entityLoadContexts != null ) {
Iterator itr = entityLoadContexts.values().iterator();
while ( itr.hasNext() ) {
EntityLoadContext entityLoadContext = ( EntityLoadContext ) itr.next();
LOG.failSafeEntitiesCleanup(entityLoadContext);
for ( EntityLoadContext entityLoadContext : entityLoadContexts.values() ) {
LOG.failSafeEntitiesCleanup( entityLoadContext );
entityLoadContext.cleanup();
}
entityLoadContexts.clear();
@ -180,12 +170,16 @@ public class LoadContexts {
*/
public CollectionLoadContext getCollectionLoadContext(ResultSet resultSet) {
CollectionLoadContext context = null;
if (collectionLoadContexts == null) collectionLoadContexts = IdentityMap.instantiate(8);
else context = (CollectionLoadContext)collectionLoadContexts.get(resultSet);
if ( collectionLoadContexts == null ) {
collectionLoadContexts = IdentityMap.instantiate( 8 );
}
else {
context = collectionLoadContexts.get(resultSet);
}
if ( context == null ) {
if (LOG.isTraceEnabled()) {
LOG.trace("Constructing collection load context for result set [" + resultSet + "]");
}
if (LOG.isTraceEnabled()) {
LOG.trace("Constructing collection load context for result set [" + resultSet + "]");
}
context = new CollectionLoadContext( this, resultSet );
collectionLoadContexts.put( resultSet, context );
}
@ -201,15 +195,23 @@ public class LoadContexts {
* @return The loading collection, or null if not found.
*/
public PersistentCollection locateLoadingCollection(CollectionPersister persister, Serializable ownerKey) {
LoadingCollectionEntry lce = locateLoadingCollectionEntry( new CollectionKey( persister, ownerKey, getEntityMode() ) );
LoadingCollectionEntry lce = locateLoadingCollectionEntry( new CollectionKey( persister, ownerKey ) );
if ( lce != null ) {
if (LOG.isTraceEnabled()) LOG.trace("Returning loading collection: "
+ MessageHelper.collectionInfoString(persister, ownerKey, getSession().getFactory()));
if ( LOG.isTraceEnabled() ) {
LOG.tracef(
"Returning loading collection: %s",
MessageHelper.collectionInfoString( persister, ownerKey, getSession().getFactory() )
);
}
return lce.getCollection();
}
// TODO : should really move this log statement to CollectionType, where this is used from...
if (LOG.isTraceEnabled()) LOG.trace("Creating collection wrapper: "
+ MessageHelper.collectionInfoString(persister, ownerKey, getSession().getFactory()));
if ( LOG.isTraceEnabled() ) {
LOG.tracef(
"Creating collection wrapper: %s",
MessageHelper.collectionInfoString( persister, ownerKey, getSession().getFactory() )
);
}
return null;
}
@ -231,7 +233,7 @@ public class LoadContexts {
*/
void registerLoadingCollectionXRef(CollectionKey entryKey, LoadingCollectionEntry entry) {
if ( xrefLoadingCollectionEntries == null ) {
xrefLoadingCollectionEntries = new HashMap();
xrefLoadingCollectionEntries = new HashMap<CollectionKey,LoadingCollectionEntry>();
}
xrefLoadingCollectionEntries.put( entryKey, entry );
}
@ -277,16 +279,14 @@ public class LoadContexts {
LoadingCollectionEntry locateLoadingCollectionEntry(CollectionKey key) {
if (xrefLoadingCollectionEntries == null) return null;
LOG.trace("Attempting to locate loading collection entry [" + key + "] in any result-set context");
LoadingCollectionEntry rtn = ( LoadingCollectionEntry ) xrefLoadingCollectionEntries.get( key );
LoadingCollectionEntry rtn = xrefLoadingCollectionEntries.get( key );
if (rtn == null) LOG.trace("Collection [" + key + "] not located in load context");
else LOG.trace("Collection [" + key + "] located in load context");
return rtn;
}
/*package*/void cleanupCollectionXRefs(Set entryKeys) {
Iterator itr = entryKeys.iterator();
while ( itr.hasNext() ) {
final CollectionKey entryKey = (CollectionKey) itr.next();
/*package*/void cleanupCollectionXRefs(Set<CollectionKey> entryKeys) {
for ( CollectionKey entryKey : entryKeys ) {
xrefLoadingCollectionEntries.remove( entryKey );
}
}
@ -301,7 +301,7 @@ public class LoadContexts {
entityLoadContexts = IdentityMap.instantiate( 8 );
}
else {
context = ( EntityLoadContext ) entityLoadContexts.get( resultSet );
context = entityLoadContexts.get( resultSet );
}
if ( context == null ) {
context = new EntityLoadContext( this, resultSet );

View File

@ -163,8 +163,7 @@ public class BatchFetchQueue {
public Serializable[] getCollectionBatch(
final CollectionPersister collectionPersister,
final Serializable id,
final int batchSize,
final EntityMode entityMode) {
final int batchSize) {
Serializable[] keys = new Serializable[batchSize];
keys[0] = id;
int i = 1;
@ -191,7 +190,6 @@ public class BatchFetchQueue {
final boolean isEqual = collectionPersister.getKeyType().isEqual(
id,
ce.getLoadedKey(),
entityMode,
collectionPersister.getFactory()
);
@ -245,7 +243,7 @@ public class BatchFetchQueue {
//the first id found after the given id
return ids;
}
if ( persister.getIdentifierType().isEqual( id, key.getIdentifier(), entityMode ) ) {
if ( persister.getIdentifierType().isEqual( id, key.getIdentifier() ) ) {
end = i;
}
else {

View File

@ -46,6 +46,16 @@ public final class CollectionKey implements Serializable {
private final int hashCode;
private EntityMode entityMode;
public CollectionKey(CollectionPersister persister, Serializable key) {
this(
persister.getRole(),
key,
persister.getKeyType(),
persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode(),
persister.getFactory()
);
}
public CollectionKey(CollectionPersister persister, Serializable key, EntityMode em) {
this( persister.getRole(), key, persister.getKeyType(), em, persister.getFactory() );
}
@ -67,13 +77,13 @@ public final class CollectionKey implements Serializable {
public boolean equals(Object other) {
CollectionKey that = (CollectionKey) other;
return that.role.equals(role) &&
keyType.isEqual(that.key, key, entityMode, factory);
keyType.isEqual(that.key, key, factory);
}
public int generateHashCode() {
int result = 17;
result = 37 * result + role.hashCode();
result = 37 * result + keyType.getHashCode(key, entityMode, factory);
result = 37 * result + keyType.getHashCode(key, factory);
return result;
}

View File

@ -182,7 +182,7 @@ public final class EntityEntry implements Serializable {
if ( getId() == null ) {
throw new IllegalStateException( "cannot generate an EntityKey when id is null.");
}
cachedEntityKey = new EntityKey( getId(), getPersister(), entityMode, tenantId );
cachedEntityKey = new EntityKey( getId(), getPersister(), tenantId );
}
return cachedEntityKey;
}
@ -215,12 +215,7 @@ public final class EntityEntry implements Serializable {
if ( getPersister().isVersioned() ) {
this.version = nextVersion;
getPersister().setPropertyValue(
entity,
getPersister().getVersionProperty(),
nextVersion,
entityMode
);
getPersister().setPropertyValue( entity, getPersister().getVersionProperty(), nextVersion );
}
FieldInterceptionHelper.clearDirty( entity );
@ -288,12 +283,7 @@ public final class EntityEntry implements Serializable {
loadedState[ persister.getVersionProperty() ] = version;
//noinspection deprecation
setLockMode( LockMode.FORCE ); // TODO: use LockMode.PESSIMISTIC_FORCE_INCREMENT
persister.setPropertyValue(
entity,
getPersister().getVersionProperty(),
nextVersion,
entityMode
);
persister.setPropertyValue( entity, getPersister().getVersionProperty(), nextVersion );
}
public boolean isReadOnly() {
@ -317,7 +307,7 @@ public final class EntityEntry implements Serializable {
throw new IllegalStateException( "Cannot make an immutable entity modifiable." );
}
setStatus( Status.MANAGED );
loadedState = getPersister().getPropertyValues( entity, entityMode );
loadedState = getPersister().getPropertyValues( entity );
}
}

View File

@ -29,7 +29,6 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.internal.util.compare.EqualsHelper;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
@ -46,7 +45,6 @@ public final class EntityKey implements Serializable {
private final Serializable identifier;
private final String entityName;
private final String rootEntityName;
private final EntityMode entityMode;
private final String tenantId;
private final int hashCode;
@ -64,17 +62,15 @@ public final class EntityKey implements Serializable {
*
* @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, String tenantId) {
public EntityKey(Serializable id, EntityPersister persister, String tenantId) {
if ( id == null ) {
throw new AssertionFailure( "null identifier" );
}
this.identifier = id;
this.rootEntityName = persister.getRootEntityName();
this.entityName = persister.getEntityName();
this.entityMode = entityMode;
this.tenantId = tenantId;
this.identifierType = persister.getIdentifierType();
@ -92,7 +88,6 @@ public final class EntityKey implements Serializable {
* @param identifierType The type of the identifier value
* @param batchLoadable Whether represented entity is eligible for batch loading
* @param factory The session factory
* @param entityMode The entity's entity mode
* @param tenantId The entity's tenant id (from the session that loaded it).
*/
private EntityKey(
@ -102,7 +97,6 @@ public final class EntityKey implements Serializable {
Type identifierType,
boolean batchLoadable,
SessionFactoryImplementor factory,
EntityMode entityMode,
String tenantId) {
this.identifier = identifier;
this.rootEntityName = rootEntityName;
@ -110,7 +104,6 @@ public final class EntityKey implements Serializable {
this.identifierType = identifierType;
this.isBatchLoadable = batchLoadable;
this.factory = factory;
this.entityMode = entityMode;
this.tenantId = tenantId;
this.hashCode = generateHashCode();
}
@ -118,7 +111,7 @@ public final class EntityKey implements Serializable {
private int generateHashCode() {
int result = 17;
result = 37 * result + rootEntityName.hashCode();
result = 37 * result + identifierType.getHashCode( identifier, entityMode, factory );
result = 37 * result + identifierType.getHashCode( identifier, factory );
return result;
}
@ -138,7 +131,7 @@ public final class EntityKey implements Serializable {
public boolean equals(Object other) {
EntityKey otherKey = (EntityKey) other;
return otherKey.rootEntityName.equals(this.rootEntityName) &&
identifierType.isEqual(otherKey.identifier, this.identifier, entityMode, factory) &&
identifierType.isEqual(otherKey.identifier, this.identifier, factory) &&
EqualsHelper.equals( tenantId, otherKey.tenantId );
}
@ -167,7 +160,6 @@ public final class EntityKey implements Serializable {
oos.writeObject( entityName );
oos.writeObject( identifierType );
oos.writeBoolean( isBatchLoadable );
oos.writeObject( entityMode.toString() );
oos.writeObject( tenantId );
}
@ -193,7 +185,6 @@ public final class EntityKey implements Serializable {
( Type ) ois.readObject(),
ois.readBoolean(),
( session == null ? null : session.getFactory() ),
EntityMode.parse( (String) ois.readObject() ),
(String) ois.readObject()
);
}

View File

@ -82,7 +82,7 @@ public class EntityUniqueKey implements Serializable {
int result = 17;
result = 37 * result + entityName.hashCode();
result = 37 * result + uniqueKeyName.hashCode();
result = 37 * result + keyType.getHashCode(key, entityMode, factory);
result = 37 * result + keyType.getHashCode(key, factory);
return result;
}
@ -94,7 +94,7 @@ public class EntityUniqueKey implements Serializable {
EntityUniqueKey that = (EntityUniqueKey) other;
return that.entityName.equals(entityName) &&
that.uniqueKeyName.equals(uniqueKeyName) &&
keyType.isEqual(that.key, key, entityMode);
keyType.isEqual(that.key, key );
}
public String toString() {

View File

@ -39,14 +39,14 @@ import org.hibernate.type.Type;
public class FilterDefinition implements Serializable {
private final String filterName;
private final String defaultFilterCondition;
private final Map parameterTypes = new HashMap();
private final Map<String,Type> parameterTypes = new HashMap<String,Type>();
/**
* Construct a new FilterDefinition instance.
*
* @param name The name of the filter for which this configuration is in effect.
*/
public FilterDefinition(String name, String defaultCondition, Map parameterTypes) {
public FilterDefinition(String name, String defaultCondition, Map<String,Type> parameterTypes) {
this.filterName = name;
this.defaultFilterCondition = defaultCondition;
this.parameterTypes.putAll( parameterTypes );
@ -77,14 +77,14 @@ public class FilterDefinition implements Serializable {
* @return The type of the named parameter.
*/
public Type getParameterType(String parameterName) {
return (Type) parameterTypes.get(parameterName);
return parameterTypes.get(parameterName);
}
public String getDefaultFilterCondition() {
return defaultFilterCondition;
}
public Map getParameterTypes() {
public Map<String,Type> getParameterTypes() {
return parameterTypes;
}

View File

@ -25,16 +25,7 @@ package org.hibernate.engine.spi;
import java.io.Serializable;
import org.hibernate.event.spi.EventSource;
public interface NonFlushedChanges extends Serializable {
/**
* Extracts the non-flushed Changes from an EventSource into this NonFlushedChanges object.
* <p>
* @param source The session
*/
void extractFromSession(EventSource source);
/**
* Remove the non-flushed changes from this NonFlushedChanges object.
*/

View File

@ -55,7 +55,7 @@ public final class QueryParameters {
private Type[] positionalParameterTypes;
private Object[] positionalParameterValues;
private Map namedParameters;
private Map<String,TypedValue> namedParameters;
private LockOptions lockOptions;
private RowSelection rowSelection;
private boolean cacheable;
@ -88,11 +88,11 @@ public final class QueryParameters {
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] postionalParameterValues,
final Object[] positionalParameterValues,
final Object optionalObject,
final String optionalEntityName,
final Serializable optionalObjectId) {
this( positionalParameterTypes, postionalParameterValues );
this( positionalParameterTypes, positionalParameterValues );
this.optionalObject = optionalObject;
this.optionalId = optionalObjectId;
this.optionalEntityName = optionalEntityName;
@ -101,25 +101,25 @@ public final class QueryParameters {
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] postionalParameterValues) {
this( positionalParameterTypes, postionalParameterValues, null, null, false, false, false, null, null, false, null );
final Object[] positionalParameterValues) {
this( positionalParameterTypes, positionalParameterValues, null, null, false, false, false, null, null, false, null );
}
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] postionalParameterValues,
final Object[] positionalParameterValues,
final Serializable[] collectionKeys) {
this( positionalParameterTypes, postionalParameterValues, null, collectionKeys );
this( positionalParameterTypes, positionalParameterValues, null, collectionKeys );
}
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] postionalParameterValues,
final Map namedParameters,
final Object[] positionalParameterValues,
final Map<String,TypedValue> namedParameters,
final Serializable[] collectionKeys) {
this(
positionalParameterTypes,
postionalParameterValues,
positionalParameterValues,
namedParameters,
null,
null,
@ -166,7 +166,7 @@ public final class QueryParameters {
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] positionalParameterValues,
final Map namedParameters,
final Map<String,TypedValue> namedParameters,
final LockOptions lockOptions,
final RowSelection rowSelection,
final boolean isReadOnlyInitialized,
@ -195,7 +195,7 @@ public final class QueryParameters {
public QueryParameters(
final Type[] positionalParameterTypes,
final Object[] positionalParameterValues,
final Map namedParameters,
final Map<String,TypedValue> namedParameters,
final LockOptions lockOptions,
final RowSelection rowSelection,
final boolean isReadOnlyInitialized,
@ -232,7 +232,7 @@ public final class QueryParameters {
return rowSelection != null;
}
public Map getNamedParameters() {
public Map<String,TypedValue> getNamedParameters() {
return namedParameters;
}
@ -252,7 +252,7 @@ public final class QueryParameters {
return resultTransformer;
}
public void setNamedParameters(Map map) {
public void setNamedParameters(Map<String,TypedValue> map) {
namedParameters = map;
}

View File

@ -325,7 +325,6 @@ public interface SessionImplementor extends Serializable, LobCreationContext {
// copied from Session:
public EntityMode getEntityMode();
public CacheMode getCacheMode();
public void setCacheMode(CacheMode cm);
public boolean isOpen();

View File

@ -39,6 +39,10 @@ public final class TypedValue implements Serializable {
private final Object value;
private final EntityMode entityMode;
public TypedValue(Type type, Object value) {
this( type, value, EntityMode.POJO );
}
public TypedValue(Type type, Object value, EntityMode entityMode) {
this.type = type;
this.value=value;
@ -62,7 +66,7 @@ public final class TypedValue implements Serializable {
//result = 37 * result + type.hashCode();
//result = 37 * result + ( value==null ? 0 : value.hashCode() );
//return result;
return value==null ? 0 : type.getHashCode(value, entityMode);
return value==null ? 0 : type.getHashCode(value );
}
public boolean equals(Object other) {
@ -71,7 +75,7 @@ public final class TypedValue implements Serializable {
/*return that.type.equals(type) &&
EqualsHelper.equals(that.value, value);*/
return type.getReturnedClass() == that.type.getReturnedClass() &&
type.isEqual(that.value, value, entityMode);
type.isEqual(that.value, value );
}
}

View File

@ -126,9 +126,8 @@ public abstract class AbstractFlushingEventListener implements Serializable {
persistenceContext.getCollectionEntries().size()
);
new Printer( session.getFactory() ).toString(
persistenceContext.getEntitiesByKey().values().iterator(),
session.getEntityMode()
);
persistenceContext.getEntitiesByKey().values().iterator()
);
}
}
@ -376,11 +375,9 @@ public abstract class AbstractFlushingEventListener implements Serializable {
//otherwise recreate the mapping between the collection and its key
CollectionKey collectionKey = new CollectionKey(
collectionEntry.getLoadedPersister(),
collectionEntry.getLoadedKey(),
session.getEntityMode()
);
persistenceContext.getCollectionsByKey()
.put(collectionKey, persistentCollection);
collectionEntry.getLoadedKey()
);
persistenceContext.getCollectionsByKey().put(collectionKey, persistentCollection);
}
}

View File

@ -72,7 +72,7 @@ public class AbstractReassociateEventListener implements Serializable {
source.getPersistenceContext().checkUniqueness( key, object );
//get a snapshot
Object[] values = persister.getPropertyValues( object, source.getEntityMode() );
Object[] values = persister.getPropertyValues( object );
TypeHelper.deepCopy(
values,
persister.getPropertyTypes(),

View File

@ -205,7 +205,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
protected boolean invokeSaveLifecycle(Object entity, EntityPersister persister, EventSource source) {
// Sub-insertions should occur before containing insertion so
// Try to do the callback now
if ( persister.implementsLifecycle( source.getEntityMode() ) ) {
if ( persister.implementsLifecycle() ) {
LOG.debugf("Calling onSave()");
if ( ( ( Lifecycle ) entity ).onSave( source ) ) {
LOG.debugf("Insertion vetoed by onSave()");
@ -279,7 +279,7 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
}
if ( substitute ) {
persister.setPropertyValues( entity, values, source.getEntityMode() );
persister.setPropertyValues( entity, values );
}
TypeHelper.deepCopy(

View File

@ -141,7 +141,7 @@ public abstract class AbstractVisitor {
void process(Object object, EntityPersister persister)
throws HibernateException {
processEntityPropertyValues(
persister.getPropertyValues( object, getSession().getEntityMode() ),
persister.getPropertyValues( object ),
persister.getPropertyTypes()
);
}

View File

@ -120,12 +120,12 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
new OnUpdateVisitor( source, id, entity ).process( entity, persister );
version = persister.getVersion( entity, source.getEntityMode() );
version = persister.getVersion( entity );
entityEntry = persistenceContext.addEntity(
entity,
( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ),
persister.getPropertyValues( entity, source.getEntityMode() ),
persister.getPropertyValues( entity ),
key,
version,
LockMode.NONE,
@ -238,7 +238,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
final Object[] currentState;
if ( entityEntry.getLoadedState() == null ) { //ie. the entity came in from update()
currentState = persister.getPropertyValues( entity, session.getEntityMode() );
currentState = persister.getPropertyValues( entity );
}
else {
currentState = entityEntry.getLoadedState();
@ -298,7 +298,7 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
}
protected boolean invokeDeleteLifecycle(EventSource session, Object entity, EntityPersister persister) {
if ( persister.implementsLifecycle( session.getEntityMode() ) ) {
if ( persister.implementsLifecycle() ) {
LOG.debugf("Calling onDelete()");
if ( ( ( Lifecycle ) entity ).onDelete( session ) ) {
LOG.debugf("Deletion vetoed by onDelete()");

View File

@ -28,7 +28,6 @@ import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.StaleObjectStateException;
import org.hibernate.action.internal.DelayedPostInsertIdentifier;
@ -62,12 +61,8 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
/**
* make sure user didn't mangle the id
*/
public void checkId(
Object object,
EntityPersister persister,
Serializable id,
EntityMode entityMode,
SessionImplementor session) throws HibernateException {
public void checkId(Object object, EntityPersister persister, Serializable id, SessionImplementor session)
throws HibernateException {
if ( id != null && id instanceof DelayedPostInsertIdentifier ) {
// this is a situation where the entity id is assigned by a post-insert generator
@ -81,7 +76,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
if (id==null) {
throw new AssertionFailure("null id in " + persister.getEntityName() + " entry (don't flush the Session after an exception occurs)");
}
if ( !persister.getIdentifierType().isEqual( id, oid, entityMode, session.getFactory() ) ) {
if ( !persister.getIdentifierType().isEqual( id, oid, session.getFactory() ) ) {
throw new HibernateException(
"identifier of an instance of " +
persister.getEntityName() +
@ -98,7 +93,6 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
EntityEntry entry,
Object[] current,
Object[] loaded,
EntityMode entityMode,
SessionImplementor session) {
if ( persister.hasNaturalIdentifier() && entry.getStatus() != Status.READ_ONLY ) {
Object[] snapshot = null;
@ -117,7 +111,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
} else {
loadedVal = loaded[prop];
}
if ( !types[prop].isEqual( current[prop], loadedVal, entityMode ) ) {
if ( !types[prop].isEqual( current[prop], loadedVal ) ) {
throw new HibernateException(
"immutable natural identifier of an instance of " +
persister.getEntityName() +
@ -139,12 +133,11 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
final EventSource session = event.getSession();
final EntityPersister persister = entry.getPersister();
final Status status = entry.getStatus();
final EntityMode entityMode = session.getEntityMode();
final Type[] types = persister.getPropertyTypes();
final boolean mightBeDirty = entry.requiresDirtyCheck(entity);
final Object[] values = getValues( entity, entry, entityMode, mightBeDirty, session );
final Object[] values = getValues( entity, entry, mightBeDirty, session );
event.setPropertyValues(values);
@ -157,7 +150,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
if ( status != Status.DELETED ) {
// now update the object .. has to be outside the main if block above (because of collections)
if (substitute) persister.setPropertyValues( entity, values, entityMode );
if (substitute) persister.setPropertyValues( entity, values );
// Search for collections by reachability, updating their role.
// We don't want to touch collections reachable from a deleted object
@ -168,12 +161,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
}
private Object[] getValues(
Object entity,
EntityEntry entry,
EntityMode entityMode,
boolean mightBeDirty,
SessionImplementor session) {
private Object[] getValues(Object entity, EntityEntry entry, boolean mightBeDirty, SessionImplementor session) {
final Object[] loadedState = entry.getLoadedState();
final Status status = entry.getStatus();
final EntityPersister persister = entry.getPersister();
@ -187,12 +175,12 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
values = loadedState;
}
else {
checkId( entity, persister, entry.getId(), entityMode, session );
checkId( entity, persister, entry.getId(), session );
// grab its current state
values = persister.getPropertyValues( entity, entityMode );
values = persister.getPropertyValues( entity );
checkNaturalId( persister, entry, values, loadedState, entityMode, session );
checkNaturalId( persister, entry, values, loadedState, session );
}
return values;
}
@ -247,7 +235,6 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
final EventSource session = event.getSession();
final Object entity = event.getEntity();
final Status status = entry.getStatus();
final EntityMode entityMode = session.getEntityMode();
final EntityPersister persister = entry.getPersister();
final Object[] values = event.getPropertyValues();
@ -291,7 +278,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
dirtyProperties,
event.hasDirtyCollection(),
( status == Status.DELETED && ! entry.isModifiableEntity() ?
persister.getPropertyValues( entity, entityMode ) :
persister.getPropertyValues( entity ) :
entry.getLoadedState() ),
entry.getVersion(),
nextVersion,
@ -502,8 +489,7 @@ public class DefaultFlushEntityEventListener implements FlushEntityEventListener
// - entry.getDeletedState() contains the entity's current property values with
// references to transient entities set to null.
// - dirtyProperties will only contain properties that refer to transient entities
final Object[] currentState =
persister.getPropertyValues( event.getEntity(), event.getSession().getEntityMode() );
final Object[] currentState = persister.getPropertyValues( event.getEntity() );
dirtyProperties = persister.findDirty( entry.getDeletedState(), currentState, entity, session );
cannotDirtyCheck = false;
}

View File

@ -27,35 +27,34 @@ import java.io.Serializable;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TypeMismatchException;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.engine.internal.TwoPhaseLoad;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.Status;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventSource;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.LoadEvent;
import org.hibernate.event.spi.LoadEventListener;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.LockMode;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TypeMismatchException;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cache.spi.entry.CacheEntry;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.internal.TwoPhaseLoad;
import org.hibernate.event.spi.EventType;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.type.EmbeddedComponentType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
@ -104,42 +103,35 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
}
final Class idClass = persister.getIdentifierType().getReturnedClass();
if ( persister.getIdentifierType().isComponentType() && EntityMode.DOM4J == event.getSession().getEntityMode() ) {
// skip this check for composite-ids relating to dom4j entity-mode;
// alternatively, we could add a check to make sure the incoming id value is
// an instance of Element...
}
else {
if ( idClass != null && ! idClass.isInstance( event.getEntityId() ) ) {
// we may have the kooky jpa requirement of allowing find-by-id where
// "id" is the "simple pk value" of a dependent objects parent. This
// is part of its generally goofy "derived identity" "feature"
if ( persister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
final EmbeddedComponentType dependentIdType =
(EmbeddedComponentType) persister.getEntityMetamodel().getIdentifierProperty().getType();
if ( dependentIdType.getSubtypes().length == 1 ) {
final Type singleSubType = dependentIdType.getSubtypes()[0];
if ( singleSubType.isEntityType() ) {
final EntityType dependentParentType = (EntityType) singleSubType;
final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( source.getFactory() );
if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
// yep that's what we have...
loadByDerivedIdentitySimplePkValue(
event,
loadType,
persister,
dependentIdType,
source.getFactory().getEntityPersister( dependentParentType.getAssociatedEntityName() )
);
return;
}
if ( idClass != null && ! idClass.isInstance( event.getEntityId() ) ) {
// we may have the kooky jpa requirement of allowing find-by-id where
// "id" is the "simple pk value" of a dependent objects parent. This
// is part of its generally goofy "derived identity" "feature"
if ( persister.getEntityMetamodel().getIdentifierProperty().isEmbedded() ) {
final EmbeddedComponentType dependentIdType =
(EmbeddedComponentType) persister.getEntityMetamodel().getIdentifierProperty().getType();
if ( dependentIdType.getSubtypes().length == 1 ) {
final Type singleSubType = dependentIdType.getSubtypes()[0];
if ( singleSubType.isEntityType() ) {
final EntityType dependentParentType = (EntityType) singleSubType;
final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( source.getFactory() );
if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
// yep that's what we have...
loadByDerivedIdentitySimplePkValue(
event,
loadType,
persister,
dependentIdType,
source.getFactory().getEntityPersister( dependentParentType.getAssociatedEntityName() )
);
return;
}
}
}
throw new TypeMismatchException(
"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass + ", got " + event.getEntityId().getClass()
);
}
throw new TypeMismatchException(
"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass + ", got " + event.getEntityId().getClass()
);
}
final EntityKey keyToLoad = source.generateEntityKey( event.getEntityId(), persister );
@ -176,7 +168,7 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
final Object parent = doLoad( event, parentPersister, parentEntityKey, options );
final Serializable dependent = (Serializable) dependentIdType.instantiate( parent, event.getSession() );
dependentIdType.setPropertyValues( dependent, new Object[] {parent}, event.getSession().getEntityMode() );
dependentIdType.setPropertyValues( dependent, new Object[] {parent}, dependentPersister.getEntityMode() );
final EntityKey dependentEntityKey = event.getSession().generateEntityKey( dependent, dependentPersister );
event.setEntityId( dependent );
@ -500,9 +492,8 @@ public class DefaultLoadEventListener extends AbstractLockUpgradeEventListener i
}
}
if ( options.isAllowNulls() ) {
// EntityPersister persister = event.getSession().getFactory().getEntityPersister( event.getEntityClassName() );
EntityPersister persister = event.getSession().getFactory().getEntityPersister( keyToLoad.getEntityName() );
if ( ! persister.isInstance( old, event.getSession().getEntityMode() ) ) {
final EntityPersister persister = event.getSession().getFactory().getEntityPersister( keyToLoad.getEntityName() );
if ( ! persister.isInstance( old ) ) {
return INCONSISTENT_RTN_CLASS_MARKER;
}
}

View File

@ -63,8 +63,7 @@ import org.hibernate.type.TypeHelper;
*
* @author Gavin King
*/
public class DefaultMergeEventListener extends AbstractSaveEventListener
implements MergeEventListener {
public class DefaultMergeEventListener extends AbstractSaveEventListener implements MergeEventListener {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
DefaultMergeEventListener.class.getName());
@ -339,8 +338,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
}
catch (PropertyValueException ex) {
String propertyName = ex.getPropertyName();
Object propertyFromCopy = persister.getPropertyValue( copy, propertyName, source.getEntityMode() );
Object propertyFromEntity = persister.getPropertyValue( entity, propertyName, source.getEntityMode() );
Object propertyFromCopy = persister.getPropertyValue( copy, propertyName );
Object propertyFromEntity = persister.getPropertyValue( entity, propertyName );
Type propertyType = persister.getPropertyType( propertyName );
EntityEntry copyEntry = source.getPersistenceContext().getEntry( copy );
if ( propertyFromCopy == null ||
@ -354,11 +353,13 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
+ (propertyFromCopy == null ? "null" : propertyFromCopy));
LOG.trace("Property '" + copyEntry.getEntityName() + "." + propertyName + "' is"
+ (propertyType.isEntityType() ? "" : " not") + " an entity type");
if (propertyFromEntity != null && !copyCache.containsKey(propertyFromEntity)) LOG.trace("Property '"
+ copyEntry.getEntityName()
+ "."
+ propertyName
+ "' is not in copy cache");
if (propertyFromEntity != null && !copyCache.containsKey(propertyFromEntity)) {
LOG.tracef(
"Property '%s.%s' is not in copy cache",
copyEntry.getEntityName(),
propertyName
);
}
}
if ( isNullabilityCheckedGlobal( source ) ) {
throw ex;
@ -440,7 +441,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
else {
// check that entity id = requestedId
Serializable entityId = persister.getIdentifier( entity, source );
if ( !persister.getIdentifierType().isEqual( id, entityId, source.getEntityMode(), source.getFactory() ) ) {
if ( !persister.getIdentifierType().isEqual( id, entityId, source.getFactory() ) ) {
throw new HibernateException( "merge requested with id not matching id of passed entity" );
}
}
@ -450,7 +451,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
//we must clone embedded composite identifiers, or
//we will get back the same instance that we pass in
final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType()
.deepCopy( id, source.getEntityMode(), source.getFactory() );
.deepCopy( id, source.getFactory() );
final Object result = source.get(entityName, clonedIdentifier);
source.setFetchProfile(previousFetchProfile);
@ -523,9 +524,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
// (though during a seperate operation) in which it was
// originally persisted/saved
boolean changed = ! persister.getVersionType().isSame(
persister.getVersion( target, source.getEntityMode() ),
persister.getVersion( entity, source.getEntityMode() ),
source.getEntityMode()
persister.getVersion( target ),
persister.getVersion( entity )
);
// TODO : perhaps we should additionally require that the incoming entity
@ -554,15 +554,15 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
final SessionImplementor source,
final Map copyCache) {
final Object[] copiedValues = TypeHelper.replace(
persister.getPropertyValues( entity, source.getEntityMode() ),
persister.getPropertyValues( target, source.getEntityMode() ),
persister.getPropertyValues( entity ),
persister.getPropertyValues( target ),
persister.getPropertyTypes(),
source,
target,
copyCache
);
persister.setPropertyValues( target, copiedValues, source.getEntityMode() );
persister.setPropertyValues( target, copiedValues );
}
protected void copyValues(
@ -580,8 +580,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
// replacement to associations types (value types were already replaced
// during the first pass)
copiedValues = TypeHelper.replaceAssociations(
persister.getPropertyValues( entity, source.getEntityMode() ),
persister.getPropertyValues( target, source.getEntityMode() ),
persister.getPropertyValues( entity ),
persister.getPropertyValues( target ),
persister.getPropertyTypes(),
source,
target,
@ -591,8 +591,8 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
}
else {
copiedValues = TypeHelper.replace(
persister.getPropertyValues( entity, source.getEntityMode() ),
persister.getPropertyValues( target, source.getEntityMode() ),
persister.getPropertyValues( entity ),
persister.getPropertyValues( target ),
persister.getPropertyTypes(),
source,
target,
@ -601,7 +601,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener
);
}
persister.setPropertyValues( target, copiedValues, source.getEntityMode() );
persister.setPropertyValues( target, copiedValues );
}
/**

View File

@ -68,7 +68,7 @@ public class DefaultPostLoadEventListener implements PostLoadEventListener {
event.getSession().getActionQueue().registerProcess( verifyVersion );
}
if ( event.getPersister().implementsLifecycle( event.getSession().getEntityMode() ) ) {
if ( event.getPersister().implementsLifecycle() ) {
//log.debug( "calling onLoad()" );
( ( Lifecycle ) event.getEntity() ).onLoad( event.getSession(), event.getId() );
}

View File

@ -110,7 +110,7 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp
boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion(
entity,
realOldVersion,
persister.getVersion( entity, source.getEntityMode() ),
persister.getVersion( entity ),
persister.getVersionType()
);

View File

@ -138,7 +138,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
else {
final boolean isEqual = !entityEntry.getPersister().getIdentifierType()
.isEqual( requestedId, entityEntry.getId(), event.getSession().getEntityMode(), factory );
.isEqual( requestedId, entityEntry.getId(), factory );
if ( isEqual ) {
throw new PersistentObjectException(
@ -309,14 +309,17 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
entry.getState(); //TODO: half-assemble this stuff
}*/
source.getPersistenceContext().addEntity(entity, (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY), null, // cachedState,
key,
persister.getVersion(entity, source.getEntityMode()),
LockMode.NONE,
true,
persister,
false,
true // assume true, since we don't really know, and it doesn't matter
source.getPersistenceContext().addEntity(
entity,
(persister.isMutable() ? Status.MANAGED : Status.READ_ONLY),
null, // cachedState,
key,
persister.getVersion( entity ),
LockMode.NONE,
true,
persister,
false,
true // assume true, since we don't really know, and it doesn't matter
);
persister.afterReassociate(entity, source);
@ -328,7 +331,7 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
}
protected boolean invokeUpdateLifecycle(Object entity, EntityPersister persister, EventSource source) {
if ( persister.implementsLifecycle( source.getEntityMode() ) ) {
if ( persister.implementsLifecycle() ) {
LOG.debugf("Calling onUpdate()");
if (((Lifecycle)entity).onUpdate(source)) {
LOG.debugf("Update vetoed by onUpdate()");

View File

@ -51,7 +51,7 @@ import org.hibernate.internal.util.collections.IdentityMap;
* @author Gail Badner
*/
class EventCache implements Map {
private Map entityToCopyMap = IdentityMap.instantiate(10);
private IdentityMap entityToCopyMap = IdentityMap.instantiate(10);
// key is an entity involved with the operation performed by the listener;
// value can be either a copy of the entity or the entity itself
@ -245,7 +245,7 @@ class EventCache implements Map {
* Returns the copy-entity mappings
* @return the copy-entity mappings
*/
public Map invertMap() {
public IdentityMap invertMap() {
return IdentityMap.invert( entityToCopyMap );
}
}

View File

@ -60,7 +60,7 @@ public class EvictVisitor extends AbstractVisitor {
public void evictCollection(Object value, CollectionType type) {
final Object pc;
if ( type.hasHolder( getSession().getEntityMode() ) ) {
if ( type.hasHolder() ) {
pc = getSession().getPersistenceContext().removeCollectionHolder(value);
}
else if ( value instanceof PersistentCollection ) {
@ -83,7 +83,7 @@ public class EvictVisitor extends AbstractVisitor {
if ( ce.getLoadedPersister() != null && ce.getLoadedKey() != null ) {
//TODO: is this 100% correct?
getSession().getPersistenceContext().getCollectionsByKey().remove(
new CollectionKey( ce.getLoadedPersister(), ce.getLoadedKey(), getSession().getEntityMode() )
new CollectionKey( ce.getLoadedPersister(), ce.getLoadedKey() )
);
}
}

View File

@ -49,7 +49,7 @@ public class FlushVisitor extends AbstractVisitor {
if (collection!=null) {
final PersistentCollection coll;
if ( type.hasHolder( getSession().getEntityMode() ) ) {
if ( type.hasHolder() ) {
coll = getSession().getPersistenceContext().getCollectionHolder(collection);
}
else {

View File

@ -112,9 +112,12 @@ public abstract class ReattachVisitor extends ProxyVisitor {
* @return
*/
final Serializable extractCollectionKeyFromOwner(CollectionPersister role) {
if (role.getCollectionType().useLHSPrimaryKey()) return ownerIdentifier;
return (Serializable)role.getOwnerEntityPersister().getPropertyValue(owner,
role.getCollectionType().getLHSPropertyName(),
getSession().getEntityMode());
if ( role.getCollectionType().useLHSPrimaryKey() ) {
return ownerIdentifier;
}
return (Serializable)role.getOwnerEntityPersister().getPropertyValue(
owner,
role.getCollectionType().getLHSPropertyName()
);
}
}

View File

@ -91,7 +91,7 @@ public class WrapVisitor extends ProxyVisitor {
final PersistenceContext persistenceContext = session.getPersistenceContext();
//TODO: move into collection type, so we can use polymorphism!
if ( collectionType.hasHolder( session.getEntityMode() ) ) {
if ( collectionType.hasHolder() ) {
if (collection==CollectionType.UNFETCHED_COLLECTION) return null;
@ -143,7 +143,7 @@ public class WrapVisitor extends ProxyVisitor {
}
}
if (substituteComponent) {
componentType.setPropertyValues( component, values, getSession().getEntityMode() );
componentType.setPropertyValues( component, values, EntityMode.POJO );
}
}
@ -152,12 +152,11 @@ public class WrapVisitor extends ProxyVisitor {
@Override
void process(Object object, EntityPersister persister) throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
Object[] values = persister.getPropertyValues( object, entityMode );
Type[] types = persister.getPropertyTypes();
processEntityPropertyValues(values, types);
final Object[] values = persister.getPropertyValues( object );
final Type[] types = persister.getPropertyTypes();
processEntityPropertyValues( values, types );
if ( isSubstitutionRequired() ) {
persister.setPropertyValues( object, values, entityMode );
persister.setPropertyValues( object, values );
}
}
}

View File

@ -95,7 +95,7 @@ public class ForeignGenerator implements IdentifierGenerator, Configurable {
Session session = ( Session ) sessionImplementor;
final EntityPersister persister = sessionImplementor.getFactory().getEntityPersister( entityName );
Object associatedObject = persister.getPropertyValue( object, propertyName, session.getEntityMode() );
Object associatedObject = persister.getPropertyValue( object, propertyName );
if ( associatedObject == null ) {
throw new IdentifierGenerationException(
"attempted to assign id from null one-to-one property [" + getRole() + "]"

View File

@ -134,7 +134,7 @@ public class SelectGenerator extends AbstractPostInsertGenerator implements Conf
SessionImplementor session,
PreparedStatement ps,
Object entity) throws SQLException {
Object uniqueKeyValue = persister.getPropertyValue( entity, uniqueKeyPropertyName, session.getEntityMode() );
Object uniqueKeyValue = persister.getPropertyValue( entity, uniqueKeyPropertyName );
uniqueKeyType.nullSafeSet( ps, uniqueKeyValue, 1, session );
}

View File

@ -84,7 +84,7 @@ public abstract class AbstractQueryImpl implements Query {
// parameter bind values...
private List values = new ArrayList(4);
private List types = new ArrayList(4);
private Map namedParameters = new HashMap(4);
private Map<String,TypedValue> namedParameters = new HashMap<String, TypedValue>(4);
private Map namedParameterLists = new HashMap(4);
private Object optionalObject;
@ -403,7 +403,7 @@ public abstract class AbstractQueryImpl implements Query {
throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]");
}
else {
namedParameters.put( name, new TypedValue( type, val, session.getEntityMode() ) );
namedParameters.put( name, new TypedValue( type, val ) );
return this;
}
}
@ -725,7 +725,7 @@ public abstract class AbstractQueryImpl implements Query {
if ( !parameterMetadata.getNamedParameterNames().contains( name ) ) {
throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]");
}
namedParameterLists.put( name, new TypedValue( type, vals, session.getEntityMode() ) );
namedParameterLists.put( name, new TypedValue( type, vals ) );
return this;
}
@ -779,7 +779,7 @@ public abstract class AbstractQueryImpl implements Query {
if ( vals.size() == 1 && isEnclosedInParens ) {
// short-circuit for performance when only 1 value and the
// placeholder is already enclosed in parentheses...
namedParamsCopy.put( name, new TypedValue( type, vals.iterator().next(), session.getEntityMode() ) );
namedParamsCopy.put( name, new TypedValue( type, vals.iterator().next() ) );
return query;
}
@ -788,7 +788,7 @@ public abstract class AbstractQueryImpl implements Query {
int i = 0;
while ( iter.hasNext() ) {
String alias = ( isJpaPositionalParam ? 'x' + name : name ) + i++ + '_';
namedParamsCopy.put( alias, new TypedValue( type, iter.next(), session.getEntityMode() ) );
namedParamsCopy.put( alias, new TypedValue( type, iter.next() ) );
list.append( ParserHelper.HQL_VARIABLE_PREFIX ).append( alias );
if ( iter.hasNext() ) {
list.append( ", " );

View File

@ -237,12 +237,12 @@ public abstract class AbstractSessionImpl implements Serializable, SharedSession
@Override
public EntityKey generateEntityKey(Serializable id, EntityPersister persister) {
return new EntityKey( id, persister, getEntityMode(), getTenantIdentifier() );
return new EntityKey( id, persister, getTenantIdentifier() );
}
@Override
public CacheKey generateCacheKey(Serializable id, Type type, String entityOrRoleName) {
return new CacheKey( id, type, entityOrRoleName, getEntityMode(), getTenantIdentifier(), getFactory() );
return new CacheKey( id, type, entityOrRoleName, getTenantIdentifier(), getFactory() );
}
private transient JdbcConnectionAccess jdbcConnectionAccess;

View File

@ -45,7 +45,7 @@ public class FilterImpl implements Filter, Serializable {
private transient FilterDefinition definition;
private String filterName;
private Map parameters = new HashMap();
private Map<String,Object> parameters = new HashMap<String, Object>();
void afterDeserialize(SessionFactoryImpl factory) {
definition = factory.getFilterDefinition(filterName);
@ -75,7 +75,7 @@ public class FilterImpl implements Filter, Serializable {
return definition.getFilterName();
}
public Map getParameters() {
public Map<String,?> getParameters() {
return parameters;
}

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2009-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -37,64 +37,42 @@ import org.hibernate.event.spi.EventSource;
import org.jboss.logging.Logger;
public final class NonFlushedChangesImpl implements NonFlushedChanges {
public final class NonFlushedChangesImpl implements NonFlushedChanges, Serializable {
private static final Logger LOG = Logger.getLogger( NonFlushedChangesImpl.class.getName() );
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, NonFlushedChangesImpl.class.getName());
private transient ActionQueue actionQueue;
private transient StatefulPersistenceContext persistenceContext;
private static class SessionNonFlushedChanges implements Serializable {
private transient EntityMode entityMode;
private transient ActionQueue actionQueue;
private transient StatefulPersistenceContext persistenceContext;
public SessionNonFlushedChanges(EventSource session) {
this.entityMode = session.getEntityMode();
this.actionQueue = session.getActionQueue();
this.persistenceContext = ( StatefulPersistenceContext ) session.getPersistenceContext();
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
entityMode = EntityMode.parse( ( String ) ois.readObject() );
persistenceContext = StatefulPersistenceContext.deserialize( ois, null );
actionQueue = ActionQueue.deserialize( ois, null );
}
private void writeObject(ObjectOutputStream oos) throws IOException {
LOG.trace("Serializing SessionNonFlushedChanges");
oos.defaultWriteObject();
oos.writeObject( entityMode.toString() );
persistenceContext.serialize( oos );
actionQueue.serialize( oos );
}
}
private Map nonFlushedChangesByEntityMode = new HashMap();
public NonFlushedChangesImpl( EventSource session ) {
extractFromSession( session );
}
public void extractFromSession(EventSource session) {
if ( nonFlushedChangesByEntityMode.containsKey( session.getEntityMode() ) ) {
throw new AssertionFailure( "Already has non-flushed changes for entity mode: " + session.getEntityMode() );
}
nonFlushedChangesByEntityMode.put( session.getEntityMode(), new SessionNonFlushedChanges( session ) );
}
private SessionNonFlushedChanges getSessionNonFlushedChanges(EntityMode entityMode) {
return ( SessionNonFlushedChanges ) nonFlushedChangesByEntityMode.get( entityMode );
public NonFlushedChangesImpl(EventSource session) {
this.actionQueue = session.getActionQueue();
this.persistenceContext = ( StatefulPersistenceContext ) session.getPersistenceContext();
}
/* package-protected */
ActionQueue getActionQueue(EntityMode entityMode) {
return getSessionNonFlushedChanges( entityMode ).actionQueue;
ActionQueue getActionQueue() {
return actionQueue;
}
/* package-protected */
StatefulPersistenceContext getPersistenceContext(EntityMode entityMode) {
return getSessionNonFlushedChanges( entityMode ).persistenceContext;
StatefulPersistenceContext getPersistenceContext() {
return persistenceContext;
}
public void clear() {
nonFlushedChangesByEntityMode.clear();
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
LOG.trace( "Deserializing NonFlushedChangesImpl" );
ois.defaultReadObject();
persistenceContext = StatefulPersistenceContext.deserialize( ois, null );
actionQueue = ActionQueue.deserialize( ois, null );
}
private void writeObject(ObjectOutputStream oos) throws IOException {
LOG.trace( "Serializing NonFlushedChangesImpl" );
oos.defaultWriteObject();
persistenceContext.serialize( oos );
actionQueue.serialize( oos );
}
}

View File

@ -38,7 +38,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@ -80,25 +79,25 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.Settings;
import org.hibernate.cfg.SettingsFactory;
import org.hibernate.context.internal.ThreadLocalSessionContext;
import org.hibernate.context.spi.CurrentSessionContext;
import org.hibernate.context.internal.JTASessionContext;
import org.hibernate.context.internal.ManagedSessionContext;
import org.hibernate.context.internal.ThreadLocalSessionContext;
import org.hibernate.context.spi.CurrentSessionContext;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionRegistry;
import org.hibernate.engine.query.spi.QueryPlanCache;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.engine.ResultSetMappingDefinition;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.engine.profile.Association;
import org.hibernate.engine.profile.Fetch;
import org.hibernate.engine.profile.FetchProfile;
import org.hibernate.engine.query.spi.QueryPlanCache;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl;
import org.hibernate.engine.transaction.spi.TransactionEnvironment;
import org.hibernate.exception.spi.SQLExceptionConverter;
@ -106,9 +105,9 @@ import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDGenerator;
import org.hibernate.id.factory.IdentifierGeneratorFactory;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.integrator.spi.IntegratorService;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.collections.EmptyIterator;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
@ -125,7 +124,6 @@ import org.hibernate.persister.spi.PersisterFactory;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.integrator.spi.IntegratorService;
import org.hibernate.service.config.spi.ConfigurationService;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.jndi.spi.JndiService;
@ -201,7 +199,7 @@ public final class SessionFactoryImpl
private final transient CurrentSessionContext currentSessionContext;
private final transient SQLFunctionRegistry sqlFunctionRegistry;
private final transient SessionFactoryObserverChain observer = new SessionFactoryObserverChain();
private final transient HashMap entityNameResolvers = new HashMap();
private final transient ConcurrentHashMap<EntityNameResolver,Object> entityNameResolvers = new ConcurrentHashMap<EntityNameResolver, Object>();
private final transient QueryPlanCache queryPlanCache;
private final transient Cache cacheAccess = new CacheImpl();
private transient boolean isClosed = false;
@ -836,14 +834,10 @@ public final class SessionFactoryImpl
}
private void registerEntityNameResolvers(EntityPersister persister) {
if ( persister.getEntityMetamodel() == null || persister.getEntityMetamodel().getTuplizerMapping() == null ) {
if ( persister.getEntityMetamodel() == null || persister.getEntityMetamodel().getTuplizer() == null ) {
return;
}
Iterator itr = persister.getEntityMetamodel().getTuplizerMapping().iterateTuplizers();
while ( itr.hasNext() ) {
final EntityTuplizer tuplizer = ( EntityTuplizer ) itr.next();
registerEntityNameResolvers( tuplizer );
}
registerEntityNameResolvers( persister.getEntityMetamodel().getTuplizer() );
}
private void registerEntityNameResolvers(EntityTuplizer tuplizer) {
@ -852,25 +846,19 @@ public final class SessionFactoryImpl
return;
}
for ( int i = 0; i < resolvers.length; i++ ) {
registerEntityNameResolver( resolvers[i], tuplizer.getEntityMode() );
for ( EntityNameResolver resolver : resolvers ) {
registerEntityNameResolver( resolver );
}
}
public void registerEntityNameResolver(EntityNameResolver resolver, EntityMode entityMode) {
LinkedHashSet resolversForMode = ( LinkedHashSet ) entityNameResolvers.get( entityMode );
if ( resolversForMode == null ) {
resolversForMode = new LinkedHashSet();
entityNameResolvers.put( entityMode, resolversForMode );
}
resolversForMode.add( resolver );
private static final Object ENTITY_NAME_RESOLVER_MAP_VALUE = new Object();
public void registerEntityNameResolver(EntityNameResolver resolver) {
entityNameResolvers.put( resolver, ENTITY_NAME_RESOLVER_MAP_VALUE );
}
public Iterator iterateEntityNameResolvers(EntityMode entityMode) {
Set actualEntityNameResolvers = ( Set ) entityNameResolvers.get( entityMode );
return actualEntityNameResolvers == null
? EmptyIterator.INSTANCE
: actualEntityNameResolvers.iterator();
public Iterable<EntityNameResolver> iterateEntityNameResolvers() {
return entityNameResolvers.keySet();
}
public QueryPlanCache getQueryPlanCache() {
@ -1115,11 +1103,11 @@ public final class SessionFactoryImpl
results.add(testClassName);
}
else {
final Class mappedClass = testQueryable.getMappedClass( EntityMode.POJO );
final Class mappedClass = testQueryable.getMappedClass();
if ( mappedClass!=null && clazz.isAssignableFrom( mappedClass ) ) {
final boolean assignableSuperclass;
if ( testQueryable.isInherited() ) {
Class mappedSuperclass = getEntityPersister( testQueryable.getMappedSuperclass() ).getMappedClass( EntityMode.POJO);
Class mappedSuperclass = getEntityPersister( testQueryable.getMappedSuperclass() ).getMappedClass();
assignableSuperclass = clazz.isAssignableFrom(mappedSuperclass);
}
else {
@ -1264,8 +1252,7 @@ public final class SessionFactoryImpl
identifier,
p.getIdentifierType(),
p.getRootEntityName(),
EntityMode.POJO, // we have to assume POJO
null, // and also assume non tenancy
null, // have to assume non tenancy
SessionFactoryImpl.this
);
}
@ -1310,8 +1297,7 @@ public final class SessionFactoryImpl
ownerIdentifier,
p.getKeyType(),
p.getRole(),
EntityMode.POJO, // we have to assume POJO
null, // and also assume non tenancy
null, // have to assume non tenancy
SessionFactoryImpl.this
);
}
@ -1583,7 +1569,6 @@ public final class SessionFactoryImpl
private Interceptor interceptor;
private Connection connection;
private ConnectionReleaseMode connectionReleaseMode;
private EntityMode entityMode;
private boolean autoClose;
private boolean autoJoinTransactions = true;
private boolean flushBeforeCompletion;
@ -1596,7 +1581,6 @@ public final class SessionFactoryImpl
// set up default builder values...
this.interceptor = sessionFactory.getInterceptor();
this.connectionReleaseMode = settings.getConnectionReleaseMode();
this.entityMode = settings.getDefaultEntityMode();
this.autoClose = settings.isAutoCloseSessionEnabled();
this.flushBeforeCompletion = settings.isFlushBeforeCompletionEnabled();
}
@ -1614,7 +1598,6 @@ public final class SessionFactoryImpl
autoJoinTransactions,
sessionFactory.settings.getRegionFactory().nextTimestamp(),
interceptor,
entityMode,
flushBeforeCompletion,
autoClose,
connectionReleaseMode,
@ -1664,12 +1647,6 @@ public final class SessionFactoryImpl
return this;
}
@Override
public SessionBuilder entityMode(EntityMode entityMode) {
this.entityMode = entityMode;
return this;
}
@Override
public SessionBuilder tenantIdentifier(String tenantIdentifier) {
this.tenantIdentifier = tenantIdentifier;

View File

@ -37,7 +37,6 @@ import java.sql.Connection;
import java.sql.NClob;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@ -50,12 +49,10 @@ import org.hibernate.CacheMode;
import org.hibernate.ConnectionReleaseMode;
import org.hibernate.Criteria;
import org.hibernate.EmptyInterceptor;
import org.hibernate.EntityMode;
import org.hibernate.EntityNameResolver;
import org.hibernate.Filter;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.SessionBuilder;
import org.hibernate.Interceptor;
import org.hibernate.LobHelper;
import org.hibernate.LockMode;
@ -69,6 +66,7 @@ import org.hibernate.SQLQuery;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionException;
import org.hibernate.SharedSessionBuilder;
import org.hibernate.Transaction;
@ -78,7 +76,12 @@ import org.hibernate.UnknownProfileException;
import org.hibernate.UnresolvableObjectException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.internal.StatefulPersistenceContext;
import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.query.spi.FilterQueryPlan;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.spi.ActionQueue;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.EntityEntry;
@ -89,15 +92,12 @@ import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.Status;
import org.hibernate.engine.jdbc.LobCreationContext;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl;
import org.hibernate.engine.transaction.spi.TransactionContext;
import org.hibernate.engine.transaction.spi.TransactionCoordinator;
import org.hibernate.engine.transaction.spi.TransactionImplementor;
import org.hibernate.event.service.spi.EventListenerGroup;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.AutoFlushEvent;
import org.hibernate.event.spi.AutoFlushEventListener;
import org.hibernate.event.spi.DeleteEvent;
@ -141,8 +141,6 @@ import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.hibernate.event.service.spi.EventListenerGroup;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.stat.internal.SessionStatisticsImpl;
import org.hibernate.type.SerializationException;
@ -181,7 +179,6 @@ public final class SessionImpl
private transient ConnectionReleaseMode connectionReleaseMode;
private transient FlushMode flushMode = FlushMode.AUTO;
private transient CacheMode cacheMode = CacheMode.NORMAL;
private transient EntityMode entityMode = EntityMode.POJO;
private transient boolean autoClear; //for EJB3
private transient boolean autoJoinTransactions = true;
@ -192,35 +189,6 @@ public final class SessionImpl
private transient LoadQueryInfluencers loadQueryInfluencers;
private transient Session rootSession;
private transient Map childSessionsByEntityMode;
/**
* Constructor used in building "child sessions".
*
* @param parent The parent session
* @param entityMode
*/
private SessionImpl(SessionImpl parent, EntityMode entityMode) {
super( parent.factory, parent.getTenantIdentifier() );
this.rootSession = parent;
this.timestamp = parent.timestamp;
this.transactionCoordinator = parent.transactionCoordinator;
this.interceptor = parent.interceptor;
this.actionQueue = new ActionQueue( this );
this.entityMode = entityMode;
this.persistenceContext = new StatefulPersistenceContext( this );
this.flushBeforeCompletionEnabled = false;
this.autoCloseSessionEnabled = false;
this.connectionReleaseMode = null;
loadQueryInfluencers = new LoadQueryInfluencers( factory );
if (factory.getStatistics().isStatisticsEnabled()) factory.getStatisticsImplementor().openSession();
LOG.debugf("Opened session [%s]", entityMode);
}
/**
* Constructor used for openSession(...) processing, as well as construction
* of sessions for getCurrentSession().
@ -232,10 +200,10 @@ public final class SessionImpl
* @param autoJoinTransactions Should the session automatically join JTA transactions?
* @param timestamp The timestamp for this session
* @param interceptor The interceptor to be applied to this session
* @param entityMode The entity-mode for this session
* @param flushBeforeCompletionEnabled Should we auto flush before completion of transaction
* @param autoCloseSessionEnabled Should we auto close after completion of transaction
* @param connectionReleaseMode The mode by which we should release JDBC connections.
* @param tenantIdentifier The tenant identifier to use. May be null
*/
SessionImpl(
final Connection connection,
@ -244,15 +212,12 @@ public final class SessionImpl
final boolean autoJoinTransactions,
final long timestamp,
final Interceptor interceptor,
final EntityMode entityMode,
final boolean flushBeforeCompletionEnabled,
final boolean autoCloseSessionEnabled,
final ConnectionReleaseMode connectionReleaseMode,
final String tenantIdentifier) {
super( factory, tenantIdentifier );
this.rootSession = null;
this.timestamp = timestamp;
this.entityMode = entityMode;
this.interceptor = interceptor == null ? EmptyInterceptor.INSTANCE : interceptor;
this.actionQueue = new ActionQueue( this );
this.persistenceContext = new StatefulPersistenceContext( this );
@ -286,34 +251,6 @@ public final class SessionImpl
return new SharedSessionBuilderImpl( this );
}
public Session getSession(EntityMode entityMode) {
if ( this.entityMode == entityMode ) {
return this;
}
if ( rootSession != null ) {
return rootSession.getSession( entityMode );
}
errorIfClosed();
checkTransactionSynchStatus();
SessionImpl rtn = null;
if ( childSessionsByEntityMode == null ) {
childSessionsByEntityMode = new HashMap();
}
else {
rtn = (SessionImpl) childSessionsByEntityMode.get( entityMode );
}
if ( rtn == null ) {
rtn = new SessionImpl( this, entityMode );
childSessionsByEntityMode.put( entityMode, rtn );
}
return rtn;
}
public void clear() {
errorIfClosed();
checkTransactionSynchStatus();
@ -338,25 +275,7 @@ public final class SessionImpl
}
try {
try {
if ( childSessionsByEntityMode != null ) {
Iterator childSessions = childSessionsByEntityMode.values().iterator();
while ( childSessions.hasNext() ) {
final SessionImpl child = ( SessionImpl ) childSessions.next();
child.close();
}
}
}
catch( Throwable t ) {
// just ignore
}
if ( rootSession == null ) {
return transactionCoordinator.close();
}
else {
return null;
}
return transactionCoordinator.close();
}
finally {
setClosed();
@ -397,13 +316,6 @@ public final class SessionImpl
}
LOG.trace( "Automatically flushing session" );
flush();
if ( childSessionsByEntityMode != null ) {
Iterator iter = childSessionsByEntityMode.values().iterator();
while ( iter.hasNext() ) {
( (Session) iter.next() ).flush();
}
}
}
/**
@ -414,14 +326,7 @@ public final class SessionImpl
public NonFlushedChanges getNonFlushedChanges() throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
NonFlushedChanges nonFlushedChanges = new NonFlushedChangesImpl( this );
if ( childSessionsByEntityMode != null ) {
Iterator it = childSessionsByEntityMode.values().iterator();
while ( it.hasNext() ) {
nonFlushedChanges.extractFromSession( ( EventSource ) it.next() );
}
}
return nonFlushedChanges;
return new NonFlushedChangesImpl( this );
}
/**
@ -435,13 +340,9 @@ public final class SessionImpl
public void applyNonFlushedChanges(NonFlushedChanges nonFlushedChanges) throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
replacePersistenceContext( ( ( NonFlushedChangesImpl ) nonFlushedChanges ).getPersistenceContext( entityMode) );
replaceActionQueue( ( ( NonFlushedChangesImpl ) nonFlushedChanges ).getActionQueue( entityMode ) );
if ( childSessionsByEntityMode != null ) {
for ( Iterator it = childSessionsByEntityMode.values().iterator(); it.hasNext(); ) {
( ( SessionImpl ) it.next() ).applyNonFlushedChanges( nonFlushedChanges );
}
}
// todo : why aren't these just part of the NonFlushedChanges API ?
replacePersistenceContext( ( ( NonFlushedChangesImpl ) nonFlushedChanges ).getPersistenceContext() );
replaceActionQueue( ( ( NonFlushedChangesImpl ) nonFlushedChanges ).getActionQueue() );
}
private void replacePersistenceContext(StatefulPersistenceContext persistenceContextNew) {
@ -565,7 +466,7 @@ public final class SessionImpl
@Override
public Connection disconnect() throws HibernateException {
errorIfClosed();
LOG.debugf("Disconnecting session");
LOG.debugf( "Disconnecting session" );
return transactionCoordinator.getJdbcCoordinator().getLogicalConnection().manualDisconnect();
}
@ -610,13 +511,11 @@ public final class SessionImpl
public void beforeTransactionCompletion(TransactionImplementor hibernateTransaction) {
LOG.trace( "before transaction completion" );
actionQueue.beforeTransactionCompletion();
if ( rootSession == null ) {
try {
interceptor.beforeTransactionCompletion( hibernateTransaction );
}
catch (Throwable t) {
LOG.exceptionInBeforeTransactionCompletionInterceptor(t);
}
try {
interceptor.beforeTransactionCompletion( hibernateTransaction );
}
catch (Throwable t) {
LOG.exceptionInBeforeTransactionCompletionInterceptor(t);
}
}
@ -625,7 +524,7 @@ public final class SessionImpl
LOG.trace( "after transaction completion" );
persistenceContext.afterTransactionCompletion();
actionQueue.afterTransactionCompletion( successful );
if ( rootSession == null && hibernateTransaction != null ) {
if ( hibernateTransaction != null ) {
try {
interceptor.afterTransactionCompletion( hibernateTransaction );
}
@ -761,7 +660,7 @@ public final class SessionImpl
// lock() operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void lock(String entityName, Object object, LockMode lockMode) throws HibernateException {
fireLock( new LockEvent(entityName, object, lockMode, this) );
fireLock( new LockEvent( entityName, object, lockMode, this ) );
}
public LockRequest buildLockRequest(LockOptions lockOptions) {
@ -892,7 +791,7 @@ public final class SessionImpl
* Delete a persistent object
*/
public void delete(Object object) throws HibernateException {
fireDelete( new DeleteEvent(object, this) );
fireDelete( new DeleteEvent( object, this ) );
}
/**
@ -1058,7 +957,7 @@ public final class SessionImpl
@Override
public void refresh(String entityName, Object object) throws HibernateException {
fireRefresh( new RefreshEvent( entityName,object,this ) );
fireRefresh( new RefreshEvent( entityName, object, this ) );
}
public void refresh(Object object, LockMode lockMode) throws HibernateException {
@ -1070,7 +969,7 @@ public final class SessionImpl
}
@Override
public void refresh(String entityName, Object object, LockOptions lockOptions) throws HibernateException {
fireRefresh( new RefreshEvent(entityName, object, lockOptions, this) );
fireRefresh( new RefreshEvent( entityName, object, lockOptions, this ) );
}
public void refresh(Object object, Map refreshedAlready) throws HibernateException {
@ -1097,7 +996,7 @@ public final class SessionImpl
// replicate() operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void replicate(Object obj, ReplicationMode replicationMode) throws HibernateException {
fireReplicate( new ReplicateEvent(obj, replicationMode, this) );
fireReplicate( new ReplicateEvent( obj, replicationMode, this ) );
}
public void replicate(String entityName, Object obj, ReplicationMode replicationMode)
@ -1312,18 +1211,13 @@ public final class SessionImpl
public Object instantiate(EntityPersister persister, Serializable id) throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
Object result = interceptor.instantiate( persister.getEntityName(), entityMode, id );
Object result = interceptor.instantiate( persister.getEntityName(), persister.getEntityMetamodel().getEntityMode(), id );
if ( result == null ) {
result = persister.instantiate( id, this );
}
return result;
}
public EntityMode getEntityMode() {
checkTransactionSynchStatus();
return entityMode;
}
public void setFlushMode(FlushMode flushMode) {
errorIfClosed();
checkTransactionSynchStatus();
@ -1355,10 +1249,6 @@ public final class SessionImpl
public Transaction beginTransaction() throws HibernateException {
errorIfClosed();
// todo : should seriously consider not allowing a txn to begin from a child session
// can always route the request to the root session...
if (rootSession != null) LOG.transactionStartedOnNonRootSession();
Transaction result = getTransaction();
result.begin();
return result;
@ -1376,8 +1266,7 @@ public final class SessionImpl
// influence this decision if we were not able to based on the
// given entityName
try {
return factory.getEntityPersister( entityName )
.getSubclassEntityPersister( object, getFactory(), entityMode );
return factory.getEntityPersister( entityName ).getSubclassEntityPersister( object, getFactory() );
}
catch( HibernateException e ) {
try {
@ -1978,9 +1867,7 @@ public final class SessionImpl
entityNameResolver = new CoordinatingEntityNameResolver();
boolean isRootSession = ois.readBoolean();
connectionReleaseMode = ConnectionReleaseMode.parse( ( String ) ois.readObject() );
entityMode = EntityMode.parse( ( String ) ois.readObject() );
autoClear = ois.readBoolean();
autoJoinTransactions = ois.readBoolean();
flushMode = FlushMode.valueOf( ( String ) ois.readObject() );
@ -1991,34 +1878,18 @@ public final class SessionImpl
factory = SessionFactoryImpl.deserialize( ois );
if ( isRootSession ) {
transactionCoordinator = TransactionCoordinatorImpl.deserialize( ois, this );
}
transactionCoordinator = TransactionCoordinatorImpl.deserialize( ois, this );
persistenceContext = StatefulPersistenceContext.deserialize( ois, this );
actionQueue = ActionQueue.deserialize( ois, this );
loadQueryInfluencers = (LoadQueryInfluencers) ois.readObject();
childSessionsByEntityMode = ( Map ) ois.readObject();
// LoadQueryInfluencers.getEnabledFilters() tries to validate each enabled
// filter, which will fail when called before FilterImpl.afterDeserialize( factory );
// Instead lookup the filter by name and then call FilterImpl.afterDeserialize( factory ).
Iterator iter = loadQueryInfluencers.getEnabledFilterNames().iterator();
while ( iter.hasNext() ) {
String filterName = ( String ) iter.next();
( ( FilterImpl ) loadQueryInfluencers.getEnabledFilter( filterName ) )
.afterDeserialize( factory );
}
if ( isRootSession && childSessionsByEntityMode != null ) {
iter = childSessionsByEntityMode.values().iterator();
while ( iter.hasNext() ) {
final SessionImpl child = ( ( SessionImpl ) iter.next() );
child.rootSession = this;
child.transactionCoordinator = this.transactionCoordinator;
}
for ( String filterName : loadQueryInfluencers.getEnabledFilterNames() ) {
((FilterImpl) loadQueryInfluencers.getEnabledFilter( filterName )).afterDeserialize( factory );
}
}
@ -2033,13 +1904,11 @@ public final class SessionImpl
throw new IllegalStateException( "Cannot serialize a session while connected" );
}
LOG.trace("Serializing session");
LOG.trace( "Serializing session" );
oos.defaultWriteObject();
oos.writeBoolean( rootSession == null );
oos.writeObject( connectionReleaseMode.toString() );
oos.writeObject( entityMode.toString() );
oos.writeBoolean( autoClear );
oos.writeBoolean( autoJoinTransactions );
oos.writeObject( flushMode.toString() );
@ -2051,16 +1920,13 @@ public final class SessionImpl
factory.serialize( oos );
if ( rootSession == null ) {
transactionCoordinator.serialize( oos );
}
transactionCoordinator.serialize( oos );
persistenceContext.serialize( oos );
actionQueue.serialize( oos );
// todo : look at optimizing these...
oos.writeObject( loadQueryInfluencers );
oos.writeObject( childSessionsByEntityMode );
}
/**
@ -2163,11 +2029,6 @@ public final class SessionImpl
return connectionReleaseMode( session.connectionReleaseMode );
}
@Override
public SharedSessionBuilder entityMode() {
return entityMode( session.entityMode );
}
@Override
public SharedSessionBuilder autoJoinTransactions() {
return autoJoinTransactions( session.autoJoinTransactions );
@ -2209,11 +2070,6 @@ public final class SessionImpl
return (SharedSessionBuilder) super.connectionReleaseMode( connectionReleaseMode );
}
@Override
public SharedSessionBuilder entityMode(EntityMode entityMode) {
return (SharedSessionBuilder) super.entityMode( entityMode );
}
@Override
public SharedSessionBuilder autoJoinTransactions(boolean autoJoinTransactions) {
return (SharedSessionBuilder) super.autoJoinTransactions( autoJoinTransactions );
@ -2237,14 +2093,13 @@ public final class SessionImpl
return entityName;
}
Iterator itr = factory.iterateEntityNameResolvers( entityMode );
while ( itr.hasNext() ) {
final EntityNameResolver resolver = ( EntityNameResolver ) itr.next();
for ( EntityNameResolver resolver : factory.iterateEntityNameResolvers() ) {
entityName = resolver.resolveEntityName( entity );
if ( entityName != null ) {
break;
}
}
if ( entityName != null ) {
return entityName;
}

View File

@ -112,15 +112,15 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
public Serializable insert(String entityName, Object entity) {
errorIfClosed();
EntityPersister persister = getEntityPersister(entityName, entity);
Serializable id = persister.getIdentifierGenerator().generate(this, entity);
Object[] state = persister.getPropertyValues(entity, EntityMode.POJO);
EntityPersister persister = getEntityPersister( entityName, entity );
Serializable id = persister.getIdentifierGenerator().generate( this, entity );
Object[] state = persister.getPropertyValues( entity );
if ( persister.isVersioned() ) {
boolean substitute = Versioning.seedVersion(
state, persister.getVersionProperty(), persister.getVersionType(), this
);
if ( substitute ) {
persister.setPropertyValues( entity, state, EntityMode.POJO );
persister.setPropertyValues( entity, state );
}
}
if ( id == IdentifierGeneratorHelper.POST_INSERT_INDICATOR ) {
@ -145,7 +145,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
errorIfClosed();
EntityPersister persister = getEntityPersister(entityName, entity);
Serializable id = persister.getIdentifier( entity, this );
Object version = persister.getVersion(entity, EntityMode.POJO);
Object version = persister.getVersion( entity );
persister.delete(id, version, entity, this);
}
@ -161,13 +161,13 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
errorIfClosed();
EntityPersister persister = getEntityPersister(entityName, entity);
Serializable id = persister.getIdentifier( entity, this );
Object[] state = persister.getPropertyValues(entity, EntityMode.POJO);
Object[] state = persister.getPropertyValues( entity );
Object oldVersion;
if ( persister.isVersioned() ) {
oldVersion = persister.getVersion(entity, EntityMode.POJO);
oldVersion = persister.getVersion( entity );
Object newVersion = Versioning.increment( oldVersion, persister.getVersionType(), this );
Versioning.setVersion(state, newVersion, persister);
persister.setPropertyValues(entity, state, EntityMode.POJO);
persister.setPropertyValues( entity, state );
}
else {
oldVersion = null;
@ -419,8 +419,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
return factory.getEntityPersister( guessEntityName( object ) );
}
else {
return factory.getEntityPersister( entityName )
.getSubclassEntityPersister( object, getFactory(), EntityMode.POJO );
return factory.getEntityPersister( entityName ).getSubclassEntityPersister( object, getFactory() );
}
}

View File

@ -57,8 +57,8 @@ public final class CollectionHelper {
* @param size The size to make the map.
* @return The sized map.
*/
public static Map mapOfSize(int size) {
return new HashMap( determineProperSizing( size ), LOAD_FACTOR );
public static <K,V> Map<K,V> mapOfSize(int size) {
return new HashMap<K,V>( determineProperSizing( size ), LOAD_FACTOR );
}
/**

View File

@ -39,10 +39,11 @@ import java.util.Set;
* A <tt>Map</tt> where keys are compared by object identity,
* rather than <tt>equals()</tt>.
*/
public final class IdentityMap implements Map {
public final class IdentityMap<K,V> implements Map<K,V> {
private final Map map;
private transient Map.Entry[] entryArray = new Map.Entry[0];
private final Map<IdentityKey<K>,V> map;
@SuppressWarnings( {"unchecked"})
private transient Entry<IdentityKey<K>,V>[] entryArray = new Entry[0];
private transient boolean dirty = false;
/**
@ -52,8 +53,8 @@ public final class IdentityMap implements Map {
* @param size The size of the map
* @return Map
*/
public static Map instantiate(int size) {
return new IdentityMap( new HashMap( size ) );
public static <K,V> IdentityMap<K,V> instantiate(int size) {
return new IdentityMap<K,V>( new HashMap<IdentityKey<K>,V>( size ) );
}
/**
@ -61,10 +62,10 @@ public final class IdentityMap implements Map {
* order defined as the order in which entries were added
*
* @param size The size of the map to create
* @return
* @return The map
*/
public static Map instantiateSequenced(int size) {
return new IdentityMap( new LinkedHashMap( size ) );
public static <K,V> IdentityMap<K,V> instantiateSequenced(int size) {
return new IdentityMap<K,V>( new LinkedHashMap<IdentityKey<K>,V>( size ) );
}
/**
@ -72,7 +73,7 @@ public final class IdentityMap implements Map {
*
* @param underlyingMap The delegate map.
*/
private IdentityMap(Map underlyingMap) {
private IdentityMap(Map<IdentityKey<K>,V> underlyingMap) {
map = underlyingMap;
dirty = true;
}
@ -82,7 +83,7 @@ public final class IdentityMap implements Map {
* is safe from concurrent modification). ie. we may safely add new instances to
* the underlying <tt>Map</tt> during iteration of the <tt>entries()</tt>.
*
* @param map
* @param map The map of entries
* @return Collection
*/
public static Map.Entry[] concurrentEntries(Map map) {
@ -101,47 +102,54 @@ public final class IdentityMap implements Map {
return new KeyIterator( map.keySet().iterator() );
}
public static final class IdentityMapEntry implements java.util.Map.Entry {
IdentityMapEntry(Object key, Object value) {
public static final class IdentityMapEntry<K,V> implements java.util.Map.Entry<K,V> {
private K key;
private V value;
IdentityMapEntry(K key, V value) {
this.key=key;
this.value=value;
}
private Object key;
private Object value;
public Object getKey() {
public K getKey() {
return key;
}
public Object getValue() {
public V getValue() {
return value;
}
public Object setValue(Object value) {
Object result = this.value;
public V setValue(V value) {
V result = this.value;
this.value = value;
return result;
}
}
public static final class IdentityKey implements Serializable {
private Object key;
public static final class IdentityKey<K> implements Serializable {
private K key;
IdentityKey(Object key) {
IdentityKey(K key) {
this.key=key;
}
@SuppressWarnings( {"EqualsWhichDoesntCheckParameterClass"})
@Override
public boolean equals(Object other) {
return key == ( (IdentityKey) other ).key;
}
@Override
public int hashCode() {
return System.identityHashCode(key);
}
@Override
public String toString() {
return key.toString();
}
public Object getRealKey() {
public K getRealKey() {
return key;
}
}
@ -154,81 +162,87 @@ public final class IdentityMap implements Map {
return map.isEmpty();
}
@Override
@SuppressWarnings( {"unchecked"})
public boolean containsKey(Object key) {
IdentityKey k = new IdentityKey(key);
return map.containsKey(k);
}
@Override
public boolean containsValue(Object val) {
return map.containsValue(val);
}
public Object get(Object key) {
IdentityKey k = new IdentityKey(key);
return map.get(k);
@Override
@SuppressWarnings( {"unchecked"})
public V get(Object key) {
return map.get( new IdentityKey(key) );
}
public Object put(Object key, Object value) {
@Override
public V put(K key, V value) {
dirty = true;
return map.put( new IdentityKey(key), value );
return map.put( new IdentityKey<K>(key), value );
}
public Object remove(Object key) {
@Override
@SuppressWarnings( {"unchecked"})
public V remove(Object key) {
dirty = true;
IdentityKey k = new IdentityKey(key);
return map.remove(k);
return map.remove( new IdentityKey(key) );
}
public void putAll(Map otherMap) {
Iterator iter = otherMap.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
put( me.getKey(), me.getValue() );
@Override
public void putAll(Map<? extends K, ? extends V> otherMap) {
for ( Entry<? extends K, ? extends V> entry : otherMap.entrySet() ) {
put( entry.getKey(), entry.getValue() );
}
}
@Override
public void clear() {
dirty = true;
entryArray = null;
map.clear();
}
public Set keySet() {
@Override
public Set<K> keySet() {
// would need an IdentitySet for this!
throw new UnsupportedOperationException();
}
public Collection values() {
@Override
public Collection<V> values() {
return map.values();
}
public Set entrySet() {
Set set = new HashSet( map.size() );
Iterator iter = map.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
set.add( new IdentityMapEntry( ( (IdentityKey) me.getKey() ).key, me.getValue() ) );
@Override
public Set<Entry<K,V>> entrySet() {
Set<Entry<K,V>> set = new HashSet<Entry<K,V>>( map.size() );
for ( Entry<IdentityKey<K>, V> entry : map.entrySet() ) {
set.add( new IdentityMapEntry<K,V>( entry.getKey().getRealKey(), entry.getValue() ) );
}
return set;
}
public List entryList() {
ArrayList list = new ArrayList( map.size() );
Iterator iter = map.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
list.add( new IdentityMapEntry( ( (IdentityKey) me.getKey() ).key, me.getValue() ) );
public List<Entry<K,V>> entryList() {
ArrayList<Entry<K,V>> list = new ArrayList<Entry<K,V>>( map.size() );
for ( Entry<IdentityKey<K>, V> entry : map.entrySet() ) {
list.add( new IdentityMapEntry<K,V>( entry.getKey().getRealKey(), entry.getValue() ) );
}
return list;
}
@SuppressWarnings( {"unchecked"})
public Map.Entry[] entryArray() {
if (dirty) {
entryArray = new Map.Entry[ map.size() ];
Iterator iter = map.entrySet().iterator();
Iterator itr = map.entrySet().iterator();
int i=0;
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
while ( itr.hasNext() ) {
Map.Entry me = (Map.Entry) itr.next();
entryArray[i++] = new IdentityMapEntry( ( (IdentityKey) me.getKey() ).key, me.getValue() );
}
dirty = false;
@ -240,7 +254,7 @@ public final class IdentityMap implements Map {
* Workaround for a JDK 1.4.1 bug where <tt>IdentityHashMap</tt>s are not
* correctly deserialized.
*
* @param map
* @param map The map to serialize
* @return Object
*/
public static Object serialize(Map map) {
@ -251,11 +265,12 @@ public final class IdentityMap implements Map {
* Workaround for a JDK 1.4.1 bug where <tt>IdentityHashMap</tt>s are not
* correctly deserialized.
*
* @param o
* @return Map
* @param o the serialized map data
* @return The deserialized map
*/
public static Map deserialize(Object o) {
return new IdentityMap( (Map) o );
@SuppressWarnings( {"unchecked"})
public static <K,V> Map<K,V> deserialize(Object o) {
return new IdentityMap<K,V>( (Map<IdentityKey<K>,V>) o );
}
@Override
@ -263,30 +278,27 @@ public final class IdentityMap implements Map {
return map.toString();
}
public static Map invert(Map map) {
Map result = instantiate( map.size() );
Iterator iter = map.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
result.put( me.getValue(), me.getKey() );
public static <K,V> IdentityMap<V,K> invert(IdentityMap<K,V> map) {
IdentityMap<V,K> result = instantiate( map.size() );
for ( Entry<K, V> entry : map.entrySet() ) {
result.put( entry.getValue(), entry.getKey() );
}
return result;
}
static final class KeyIterator implements Iterator {
static final class KeyIterator<K> implements Iterator<K> {
private final Iterator<IdentityKey<K>> identityKeyIterator;
private KeyIterator(Iterator iter) {
identityKeyIterator = iter;
private KeyIterator(Iterator<IdentityKey<K>> iterator) {
identityKeyIterator = iterator;
}
private final Iterator identityKeyIterator;
public boolean hasNext() {
return identityKeyIterator.hasNext();
}
public Object next() {
return ( (IdentityKey) identityKeyIterator.next() ).key;
public K next() {
return identityKeyIterator.next().getRealKey();
}
public void remove() {

View File

@ -758,14 +758,6 @@ public abstract class Loader {
}
}
private Serializable determineResultId(SessionImplementor session, Serializable optionalId, Type idType, Serializable resolvedId) {
final boolean idIsResultId = optionalId != null
&& resolvedId != null
&& idType.isEqual( optionalId, resolvedId, session.getEntityMode(), factory );
final Serializable resultId = idIsResultId ? optionalId : resolvedId;
return resultId;
}
protected void applyPostLoadLocks(Object[] row, LockMode[] lockModesArray, SessionImplementor session) {
}
@ -1298,7 +1290,7 @@ public abstract class Loader {
final boolean idIsResultId = id != null &&
resultId != null &&
idType.isEqual( id, resultId, session.getEntityMode(), factory );
idType.isEqual( id, resultId, factory );
if ( idIsResultId ) resultId = id; //use the id passed in
}
@ -1418,15 +1410,15 @@ public abstract class Loader {
* The entity instance is already in the session cache
*/
private void instanceAlreadyLoaded(
final ResultSet rs,
final ResultSet rs,
final int i,
final Loadable persister,
final EntityKey key,
final Object object,
final LockMode lockMode,
final SessionImplementor session)
throws HibernateException, SQLException {
if ( !persister.isInstance( object, session.getEntityMode() ) ) {
throws HibernateException, SQLException {
if ( !persister.isInstance( object ) ) {
throw new WrongClassException(
"loaded object was of wrong class " + object.getClass(),
key.getIdentifier(),
@ -1588,8 +1580,9 @@ public abstract class Loader {
ukName,
type.semiResolve( values[index], session, object ),
type,
session.getEntityMode(), session.getFactory()
);
persister.getEntityMode(),
session.getFactory()
);
session.getPersistenceContext().addEntity( euk, object );
}
}
@ -2344,10 +2337,7 @@ public abstract class Loader {
return QueryKey.generateQueryKey(
getSQLString(),
queryParameters,
FilterKey.createFilterKeys(
session.getLoadQueryInfluencers().getEnabledFilters(),
session.getEntityMode()
),
FilterKey.createFilterKeys( session.getLoadQueryInfluencers().getEnabledFilters() ),
session,
createCacheableResultTransformer( queryParameters )
);

View File

@ -69,7 +69,7 @@ public class BatchingCollectionInitializer implements CollectionInitializer {
throws HibernateException {
Serializable[] batch = session.getPersistenceContext().getBatchFetchQueue()
.getCollectionBatch( collectionPersister, id, batchSizes[0], session.getEntityMode() );
.getCollectionBatch( collectionPersister, id, batchSizes[0] );
for ( int i=0; i<batchSizes.length-1; i++) {
final int smallBatchSize = batchSizes[i];

View File

@ -68,7 +68,6 @@ public class BatchingEntityLoader implements UniqueEntityLoader {
final boolean equal = idType.isEqual(
id,
session.getContextEntityIdentifier(obj),
session.getEntityMode(),
session.getFactory()
);
if ( equal ) return obj;
@ -86,8 +85,8 @@ public class BatchingEntityLoader implements UniqueEntityLoader {
public Object load(Serializable id, Object optionalObject, SessionImplementor session, LockOptions lockOptions) {
Serializable[] batch = session.getPersistenceContext()
.getBatchFetchQueue()
.getEntityBatch( persister, id, batchSizes[0], session.getEntityMode() );
.getBatchFetchQueue()
.getEntityBatch( persister, id, batchSizes[0], persister.getEntityMode() );
for ( int i=0; i<batchSizes.length-1; i++) {
final int smallBatchSize = batchSizes[i];

View File

@ -289,12 +289,7 @@ public class Property implements Serializable, MetaAttributable {
}
public String getAccessorPropertyName( EntityMode mode ) {
if ( mode == EntityMode.DOM4J ) {
return nodeName;
}
else {
return getName();
}
return getName();
}
// todo : remove

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,12 +20,12 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.metadata;
import java.io.Serializable;
import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.Type;
@ -146,15 +146,7 @@ public interface ClassMetadata {
/**
* The persistent class, or null
*/
public Class getMappedClass(EntityMode entityMode);
/**
* Create a class instance initialized with the given identifier
*
* @deprecated Use {@link #instantiate(Serializable, org.hibernate.engine.spi.SessionImplementor)} instead
* @noinspection JavaDoc
*/
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException;
public Class getMappedClass();
/**
* Create a class instance initialized with the given identifier
@ -169,34 +161,34 @@ public interface ClassMetadata {
/**
* Get the value of a particular (named) property
*/
public Object getPropertyValue(Object object, String propertyName, EntityMode entityMode) throws HibernateException;
public Object getPropertyValue(Object object, String propertyName) throws HibernateException;
/**
* Extract the property values from the given entity.
*
* @param entity The entity from which to extract the property values.
* @param entityMode The entity-mode of the given entity
* @return The property values.
* @throws HibernateException
*/
public Object[] getPropertyValues(Object entity, EntityMode entityMode) throws HibernateException;
public Object[] getPropertyValues(Object entity) throws HibernateException;
/**
* Set the value of a particular (named) property
*/
public void setPropertyValue(Object object, String propertyName, Object value, EntityMode entityMode) throws HibernateException;
public void setPropertyValue(Object object, String propertyName, Object value) throws HibernateException;
/**
* Set the given values to the mapped properties of the given object
*/
public void setPropertyValues(Object object, Object[] values, EntityMode entityMode) throws HibernateException;
public void setPropertyValues(Object object, Object[] values) throws HibernateException;
/**
* Get the identifier of an instance (throw an exception if no identifier property)
*
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead
* @noinspection JavaDoc
*/
public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException;
public Serializable getIdentifier(Object object) throws HibernateException;
/**
* Get the identifier of an instance (throw an exception if no identifier property)
@ -208,20 +200,6 @@ public interface ClassMetadata {
*/
public Serializable getIdentifier(Object entity, SessionImplementor session);
/**
* Inject the identifier value into the given entity.
* </p>
* Has no effect if the entity does not define an identifier property
*
* @param entity The entity to inject with the identifier value.
* @param id The value to be injected as the identifier.
* @param entityMode The entity mode
*
* @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
* @noinspection JavaDoc
*/
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode) throws HibernateException;
/**
* Inject the identifier value into the given entity.
*
@ -235,12 +213,12 @@ public interface ClassMetadata {
/**
* Does the class implement the <tt>Lifecycle</tt> interface?
*/
public boolean implementsLifecycle(EntityMode entityMode);
public boolean implementsLifecycle();
/**
* Get the version number (or timestamp) from the object's version property
* (or return null if not versioned)
*/
public Object getVersion(Object object, EntityMode entityMode) throws HibernateException;
public Object getVersion(Object object) throws HibernateException;
}

View File

@ -33,7 +33,6 @@ import org.hibernate.EntityMode;
*/
public class Entity extends AbstractAttributeContainer {
private final PojoEntitySpecifics pojoEntitySpecifics = new PojoEntitySpecifics();
private final Dom4jEntitySpecifics dom4jEntitySpecifics = new Dom4jEntitySpecifics();
private final MapEntitySpecifics mapEntitySpecifics = new MapEntitySpecifics();
/**
@ -57,10 +56,6 @@ public class Entity extends AbstractAttributeContainer {
return pojoEntitySpecifics;
}
public Dom4jEntitySpecifics getDom4jEntitySpecifics() {
return dom4jEntitySpecifics;
}
public MapEntitySpecifics getMapEntitySpecifics() {
return mapEntitySpecifics;
}
@ -106,31 +101,6 @@ public class Entity extends AbstractAttributeContainer {
}
}
public static class Dom4jEntitySpecifics implements EntityModeEntitySpecifics {
private String tuplizerClassName;
private String nodeName;
@Override
public EntityMode getEntityMode() {
return EntityMode.DOM4J;
}
public String getTuplizerClassName() {
return tuplizerClassName;
}
public void setTuplizerClassName(String tuplizerClassName) {
this.tuplizerClassName = tuplizerClassName;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}
public static class MapEntitySpecifics implements EntityModeEntitySpecifics {
private String tuplizerClassName;

View File

@ -129,7 +129,6 @@ abstract class AbstractEntityBinder {
// TODO: move this stuff out
// transfer an explicitly defined lazy attribute
bindPojoRepresentation( entityClazz, entityBinding );
bindDom4jRepresentation( entityClazz, entityBinding );
bindMapRepresentation( entityClazz, entityBinding );
final String entityName = entityBinding.getEntity().getName();
@ -171,20 +170,6 @@ abstract class AbstractEntityBinder {
}
}
private void bindDom4jRepresentation(XMLHibernateMapping.XMLClass entityClazz,
EntityBinding entityBinding) {
String nodeName = entityClazz.getNode();
if ( nodeName == null ) {
nodeName = StringHelper.unqualify( entityBinding.getEntity().getName() );
}
entityBinding.getEntity().getDom4jEntitySpecifics().setNodeName( nodeName );
XMLTuplizerElement tuplizer = locateTuplizerDefinition( entityClazz, EntityMode.DOM4J );
if ( tuplizer != null ) {
entityBinding.getEntity().getDom4jEntitySpecifics().setTuplizerClassName( tuplizer.getClazz() );
}
}
private void bindMapRepresentation(XMLHibernateMapping.XMLClass entityClazz,
EntityBinding entityBinding) {
XMLTuplizerElement tuplizer = locateTuplizerDefinition( entityClazz, EntityMode.MAP );

View File

@ -105,7 +105,6 @@ import org.hibernate.sql.SelectFragment;
import org.hibernate.sql.SimpleSelect;
import org.hibernate.sql.Template;
import org.hibernate.sql.Update;
import org.hibernate.tuple.Tuplizer;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.EntityTuplizer;
import org.hibernate.type.AssociationType;
@ -538,7 +537,7 @@ public abstract class AbstractEntityPersister
// PROPERTIES
final boolean lazyAvailable = isInstrumented(EntityMode.POJO);
final boolean lazyAvailable = isInstrumented();
int hydrateSpan = entityMetamodel.getPropertySpan();
propertyColumnSpans = new int[hydrateSpan];
@ -1004,10 +1003,10 @@ public abstract class AbstractEntityPersister
final Object[] snapshot,
final int j,
final Object propValue) {
setPropertyValue( entity, lazyPropertyNumbers[j], propValue, session.getEntityMode() );
if (snapshot != null) {
setPropertyValue( entity, lazyPropertyNumbers[j], propValue );
if ( snapshot != null ) {
// object have been loaded with setReadOnly(true); HHH-2236
snapshot[ lazyPropertyNumbers[j] ] = lazyPropertyTypes[j].deepCopy( propValue, session.getEntityMode(), factory );
snapshot[ lazyPropertyNumbers[j] ] = lazyPropertyTypes[j].deepCopy( propValue, factory );
}
return fieldName.equals( lazyPropertyNames[j] );
}
@ -2867,9 +2866,9 @@ public abstract class AbstractEntityPersister
// For the case of dynamic-update="false", or no snapshot, we use the static SQL
updateStrings = getUpdateStrings(
rowId != null,
hasUninitializedLazyProperties( object, session.getEntityMode() )
);
propsToUpdate = getPropertyUpdateability( object, session.getEntityMode() );
hasUninitializedLazyProperties( object )
);
propsToUpdate = getPropertyUpdateability( object );
}
for ( int j = 0; j < span; j++ ) {
@ -3443,7 +3442,7 @@ public abstract class AbstractEntityPersister
currentState,
previousState,
propertyColumnUpdateable,
hasUninitializedLazyProperties( entity, session.getEntityMode() ),
hasUninitializedLazyProperties( entity ),
session
);
if ( props == null ) {
@ -3472,7 +3471,7 @@ public abstract class AbstractEntityPersister
current,
old,
propertyColumnUpdateable,
hasUninitializedLazyProperties( entity, session.getEntityMode() ),
hasUninitializedLazyProperties( entity ),
session
);
if ( props == null ) {
@ -3488,10 +3487,10 @@ public abstract class AbstractEntityPersister
* Which properties appear in the SQL update?
* (Initialized, updateable ones!)
*/
protected boolean[] getPropertyUpdateability(Object entity, EntityMode entityMode) {
return hasUninitializedLazyProperties( entity, entityMode ) ?
getNonLazyPropertyUpdateability() :
getPropertyUpdateability();
protected boolean[] getPropertyUpdateability(Object entity) {
return hasUninitializedLazyProperties( entity )
? getNonLazyPropertyUpdateability()
: getPropertyUpdateability();
}
private void logDirtyProperties(int[] props) {
@ -3503,14 +3502,6 @@ public abstract class AbstractEntityPersister
}
}
protected EntityTuplizer getTuplizer(SessionImplementor session) {
return getTuplizer( session.getEntityMode() );
}
protected EntityTuplizer getTuplizer(EntityMode entityMode) {
return entityMetamodel.getTuplizer( entityMode );
}
public SessionFactoryImplementor getFactory() {
return factory;
}
@ -3630,7 +3621,7 @@ public abstract class AbstractEntityPersister
}
// check the version unsaved-value, if appropriate
final Object version = getVersion( entity, session.getEntityMode() );
final Object version = getVersion( entity );
if ( isVersioned() ) {
// let this take precedence if defined, since it works for
// assigned identifiers
@ -3749,7 +3740,7 @@ public abstract class AbstractEntityPersister
}
public Type getPropertyType(String propertyName) throws MappingException {
return propertyMapping.toType(propertyName);
return propertyMapping.toType( propertyName );
}
public Type getType() {
@ -3765,8 +3756,7 @@ public abstract class AbstractEntityPersister
}
public Object createProxy(Serializable id, SessionImplementor session) throws HibernateException {
return entityMetamodel.getTuplizer( session.getEntityMode() )
.createProxy( id, session );
return entityMetamodel.getTuplizer().createProxy( id, session );
}
public String toString() {
@ -3784,9 +3774,8 @@ public abstract class AbstractEntityPersister
return selectFragment( lhsAlias, entitySuffix );
}
public boolean isInstrumented(EntityMode entityMode) {
EntityTuplizer tuplizer = entityMetamodel.getTuplizerOrNull(entityMode);
return tuplizer!=null && tuplizer.isInstrumented();
public boolean isInstrumented() {
return getEntityTuplizer().isInstrumented();
}
public boolean hasInsertGeneratedProperties() {
@ -3806,7 +3795,7 @@ public abstract class AbstractEntityPersister
}
public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session) {
getTuplizer( session ).afterInitialize( entity, lazyPropertiesAreUnfetched, session );
getEntityTuplizer().afterInitialize( entity, lazyPropertiesAreUnfetched, session );
}
public String[] getPropertyNames() {
@ -3857,117 +3846,90 @@ public abstract class AbstractEntityPersister
return entityMetamodel.getCascadeStyles();
}
public final Class getMappedClass(EntityMode entityMode) {
Tuplizer tup = entityMetamodel.getTuplizerOrNull(entityMode);
return tup==null ? null : tup.getMappedClass();
public final Class getMappedClass() {
return getEntityTuplizer().getMappedClass();
}
public boolean implementsLifecycle(EntityMode entityMode) {
return getTuplizer( entityMode ).isLifecycleImplementor();
public boolean implementsLifecycle() {
return getEntityTuplizer().isLifecycleImplementor();
}
public Class getConcreteProxyClass(EntityMode entityMode) {
return getTuplizer( entityMode ).getConcreteProxyClass();
public Class getConcreteProxyClass() {
return getEntityTuplizer().getConcreteProxyClass();
}
public void setPropertyValues(Object object, Object[] values, EntityMode entityMode)
throws HibernateException {
getTuplizer( entityMode ).setPropertyValues( object, values );
public void setPropertyValues(Object object, Object[] values) {
getEntityTuplizer().setPropertyValues( object, values );
}
public void setPropertyValue(Object object, int i, Object value, EntityMode entityMode)
throws HibernateException {
getTuplizer( entityMode ).setPropertyValue( object, i, value );
public void setPropertyValue(Object object, int i, Object value) {
getEntityTuplizer().setPropertyValue( object, i, value );
}
public Object[] getPropertyValues(Object object, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).getPropertyValues( object );
public Object[] getPropertyValues(Object object) {
return getEntityTuplizer().getPropertyValues( object );
}
public Object getPropertyValue(Object object, int i, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).getPropertyValue( object , i );
@Override
public Object getPropertyValue(Object object, int i) {
return getEntityTuplizer().getPropertyValue( object, i );
}
public Object getPropertyValue(Object object, String propertyName, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).getPropertyValue( object, propertyName );
@Override
public Object getPropertyValue(Object object, String propertyName) {
return getEntityTuplizer().getPropertyValue( object, propertyName );
}
public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException {
return getTuplizer( entityMode ).getIdentifier( object, null );
@Override
public Serializable getIdentifier(Object object) {
return getEntityTuplizer().getIdentifier( object, null );
}
@Override
public Serializable getIdentifier(Object entity, SessionImplementor session) {
return getTuplizer( session.getEntityMode() ).getIdentifier( entity, session );
return getEntityTuplizer().getIdentifier( entity, session );
}
/**
* {@inheritDoc}
*/
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode)
throws HibernateException {
getTuplizer( entityMode ).setIdentifier( entity, id, null );
}
/**
* {@inheritDoc}
*/
@Override
public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
getTuplizer( session ).setIdentifier( entity, id, session );
getEntityTuplizer().setIdentifier( entity, id, session );
}
public Object getVersion(Object object, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).getVersion( object );
@Override
public Object getVersion(Object object) {
return getEntityTuplizer().getVersion( object );
}
/**
* {@inheritDoc}
*/
public Object instantiate(Serializable id, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).instantiate( id, null );
@Override
public Object instantiate(Serializable id, SessionImplementor session) {
return getEntityTuplizer().instantiate( id, session );
}
/**
* {@inheritDoc}
*/
public Object instantiate(Serializable id, SessionImplementor session)
throws HibernateException {
return getTuplizer( session ).instantiate( id, session );
@Override
public boolean isInstance(Object object) {
return getEntityTuplizer().isInstance( object );
}
public boolean isInstance(Object object, EntityMode entityMode) {
return getTuplizer( entityMode ).isInstance( object );
}
public boolean hasUninitializedLazyProperties(Object object, EntityMode entityMode) {
return getTuplizer( entityMode ).hasUninitializedLazyProperties( object );
}
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, EntityMode entityMode) {
getTuplizer( entityMode ).resetIdentifier( entity, currentId, currentVersion, null );
@Override
public boolean hasUninitializedLazyProperties(Object object) {
return getEntityTuplizer().hasUninitializedLazyProperties( object );
}
@Override
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session) {
getTuplizer( session ).resetIdentifier( entity, currentId, currentVersion, session );
getEntityTuplizer().resetIdentifier( entity, currentId, currentVersion, session );
}
/**
* {@inheritDoc}
*/
public EntityPersister getSubclassEntityPersister(
Object instance,
SessionFactoryImplementor factory,
EntityMode entityMode) {
@Override
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory) {
if ( !hasSubclasses() ) {
return this;
}
else {
final String concreteEntityName = getTuplizer( entityMode )
.determineConcreteSubclassEntityName( instance, factory );
final String concreteEntityName = getEntityTuplizer().determineConcreteSubclassEntityName(
instance,
factory
);
if ( concreteEntityName == null || getEntityName().equals( concreteEntityName ) ) {
// the contract of EntityTuplizer.determineConcreteSubclassEntityName says that returning null
// is an indication that the specified entity-name (this.getEntityName) should be used.
@ -3979,10 +3941,6 @@ public abstract class AbstractEntityPersister
}
}
public EntityMode guessEntityMode(Object object) {
return entityMetamodel.guessEntityMode(object);
}
public boolean isMultiTable() {
return false;
}
@ -4000,7 +3958,7 @@ public abstract class AbstractEntityPersister
}
public Object[] getPropertyValuesToInsert(Object object, Map mergeMap, SessionImplementor session) throws HibernateException {
return getTuplizer( session.getEntityMode() ).getPropertyValuesToInsert( object, mergeMap, session );
return getEntityTuplizer().getPropertyValuesToInsert( object, mergeMap, session );
}
public void processInsertGeneratedProperties(Serializable id, Object entity, Object[] state, SessionImplementor session) {
@ -4046,7 +4004,7 @@ public abstract class AbstractEntityPersister
if ( includeds[i] != ValueInclusion.NONE ) {
Object hydratedState = getPropertyTypes()[i].hydrate( rs, getPropertyAliases( "", i ), session, entity );
state[i] = getPropertyTypes()[i].resolve( hydratedState, session, entity );
setPropertyValue( entity, i, state[i], session.getEntityMode() );
setPropertyValue( entity, i, state[i] );
}
}
}
@ -4173,12 +4131,22 @@ public abstract class AbstractEntityPersister
}
return concretePropertySelectFragment;
}
public boolean hasNaturalIdentifier() {
return entityMetamodel.hasNaturalIdentifier();
}
public void setPropertyValue(Object object, String propertyName, Object value, EntityMode entityMode)
throws HibernateException {
getTuplizer( entityMode ).setPropertyValue( object, propertyName, value );
public void setPropertyValue(Object object, String propertyName, Object value) {
getEntityTuplizer().setPropertyValue( object, propertyName, value );
}
@Override
public EntityMode getEntityMode() {
return entityMetamodel.getEntityMode();
}
@Override
public EntityTuplizer getEntityTuplizer() {
return entityMetamodel.getTuplizer();
}
}

View File

@ -86,8 +86,9 @@ public class DiscriminatorType extends AbstractType {
if ( entityName == null ) {
throw new HibernateException( "Unable to resolve discriminator value [" + discriminatorValue + "] to entity name" );
}
if ( EntityMode.POJO.equals( session.getEntityMode() ) ) {
return session.getEntityPersister( entityName, null ).getMappedClass( session.getEntityMode() );
final EntityPersister entityPersister = session.getEntityPersister( entityName, null );
if ( EntityMode.POJO == entityPersister.getEntityMode() ) {
return entityPersister.getMappedClass();
}
else {
return entityName;
@ -117,7 +118,7 @@ public class DiscriminatorType extends AbstractType {
return value == null ? "[null]" : value.toString();
}
public Object deepCopy(Object value, EntityMode entityMode, SessionFactoryImplementor factory)
public Object deepCopy(Object value, SessionFactoryImplementor factory)
throws HibernateException {
return value;
}

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,12 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.persister.entity;
import java.io.Serializable;
import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
@ -40,6 +41,7 @@ import org.hibernate.engine.spi.ValueInclusion;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.EntityTuplizer;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
@ -499,15 +501,10 @@ public interface EntityPersister extends OptimisticCacheSource {
public Object forceVersionIncrement(Serializable id, Object currentVersion, SessionImplementor session)
throws HibernateException;
/**
* Try to discover the entity mode from the entity instance
*/
public EntityMode guessEntityMode(Object object);
/**
* Has the class actually been bytecode instrumented?
*/
public boolean isInstrumented(EntityMode entityMode);
public boolean isInstrumented();
/**
* Does this entity define any properties as being database generated on insert?
@ -606,50 +603,51 @@ public interface EntityPersister extends OptimisticCacheSource {
/**
* The persistent class, or null
*/
public Class getMappedClass(EntityMode entityMode);
public Class getMappedClass();
/**
* Does the class implement the <tt>Lifecycle</tt> interface.
* Does the class implement the {@link org.hibernate.classic.Lifecycle} interface.
*/
public boolean implementsLifecycle(EntityMode entityMode);
public boolean implementsLifecycle();
/**
* Get the proxy interface that instances of <em>this</em> concrete class will be
* cast to (optional operation).
*/
public Class getConcreteProxyClass(EntityMode entityMode);
public Class getConcreteProxyClass();
/**
* Set the given values to the mapped properties of the given object
*/
public void setPropertyValues(Object object, Object[] values, EntityMode entityMode) throws HibernateException;
public void setPropertyValues(Object object, Object[] values);
/**
* Set the value of a particular property
*/
public void setPropertyValue(Object object, int i, Object value, EntityMode entityMode) throws HibernateException;
public void setPropertyValue(Object object, int i, Object value);
/**
* Return the (loaded) values of the mapped properties of the object (not including backrefs)
*/
public Object[] getPropertyValues(Object object, EntityMode entityMode) throws HibernateException;
public Object[] getPropertyValues(Object object);
/**
* Get the value of a particular property
*/
public Object getPropertyValue(Object object, int i, EntityMode entityMode) throws HibernateException;
public Object getPropertyValue(Object object, int i) throws HibernateException;
/**
* Get the value of a particular property
*/
public Object getPropertyValue(Object object, String propertyName, EntityMode entityMode) throws HibernateException;
public Object getPropertyValue(Object object, String propertyName);
/**
* Get the identifier of an instance (throw an exception if no identifier property)
*
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead
* @noinspection JavaDoc
*/
public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException;
public Serializable getIdentifier(Object object) throws HibernateException;
/**
* Get the identifier of an instance (throw an exception if no identifier property)
@ -661,20 +659,6 @@ public interface EntityPersister extends OptimisticCacheSource {
*/
public Serializable getIdentifier(Object entity, SessionImplementor session);
/**
* Inject the identifier value into the given entity.
* </p>
* Has no effect if the entity does not define an identifier property
*
* @param entity The entity to inject with the identifier value.
* @param id The value to be injected as the identifier.
* @param entityMode The entity mode
*
* @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
* @noinspection JavaDoc
*/
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode) throws HibernateException;
/**
* Inject the identifier value into the given entity.
*
@ -687,15 +671,7 @@ public interface EntityPersister extends OptimisticCacheSource {
/**
* Get the version number (or timestamp) from the object's version property (or return null if not versioned)
*/
public Object getVersion(Object object, EntityMode entityMode) throws HibernateException;
/**
* Create a class instance initialized with the given identifier
*
* @deprecated Use {@link #instantiate(Serializable, SessionImplementor)} instead
* @noinspection JavaDoc
*/
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException;
public Object getVersion(Object object) throws HibernateException;
/**
* Create a class instance initialized with the given identifier
@ -710,24 +686,12 @@ public interface EntityPersister extends OptimisticCacheSource {
/**
* Is the given object an instance of this entity?
*/
public boolean isInstance(Object object, EntityMode entityMode);
public boolean isInstance(Object object);
/**
* Does the given instance have any uninitialized lazy properties?
*/
public boolean hasUninitializedLazyProperties(Object object, EntityMode entityMode);
/**
* Set the identifier and version of the given instance back to its "unsaved" value.
*
* @param entity The entity instance
* @param currentId The currently assigned identifier value.
* @param currentVersion The currently assigned version value.
* @param entityMode The entity mode represented by the entity instance.
*
* @deprecated Use {@link #resetIdentifier(Object, Serializable, Object, SessionImplementor)} instead
*/
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, EntityMode entityMode);
public boolean hasUninitializedLazyProperties(Object object);
/**
* Set the identifier and version of the given instance back to its "unsaved" value.
@ -753,12 +717,14 @@ public interface EntityPersister extends OptimisticCacheSource {
*
* @param instance The entity instance
* @param factory Reference to the SessionFactory
* @param entityMode The entity mode represented by the entity instance.
*
* @return The appropriate persister
*
* @throws HibernateException Indicates that instance was deemed to not be a subclass of the entity mapped by
* this persister.
*/
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode);
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory);
public EntityMode getEntityMode();
public EntityTuplizer getEntityTuplizer();
}

View File

@ -231,7 +231,7 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
ArrayHelper.toStringArray( persistentClass.getSynchronizedTables() )
);
final boolean lazyAvailable = isInstrumented(EntityMode.POJO);
final boolean lazyAvailable = isInstrumented();
boolean hasDeferred = false;
ArrayList subclassTables = new ArrayList();

View File

@ -23,20 +23,20 @@
*
*/
package org.hibernate.pretty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.EntityMode;
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Renders entities to a nicely readable string.
@ -51,25 +51,27 @@ public final class Printer {
/**
* @param entity an actual entity object, not a proxy!
*/
public String toString(Object entity, EntityMode entityMode) throws HibernateException {
public String toString(Object entity) throws HibernateException {
// todo : this call will not work for anything other than pojos!
ClassMetadata cm = factory.getClassMetadata( entity.getClass() );
// need a means to access the entity name resolver(s). problem is accounting for session interceptor from here...
EntityPersister entityPersister = factory.getEntityPersister( entity.getClass().getName() );
if ( cm==null ) return entity.getClass().getName();
if ( entityPersister == null ) {
return entity.getClass().getName();
}
Map result = new HashMap();
Map<String,String> result = new HashMap<String,String>();
if ( cm.hasIdentifierProperty() ) {
if ( entityPersister.hasIdentifierProperty() ) {
result.put(
cm.getIdentifierPropertyName(),
cm.getIdentifierType().toLoggableString( cm.getIdentifier( entity, entityMode ), factory )
entityPersister.getIdentifierPropertyName(),
entityPersister.getIdentifierType().toLoggableString( entityPersister.getIdentifier( entity ), factory )
);
}
Type[] types = cm.getPropertyTypes();
String[] names = cm.getPropertyNames();
Object[] values = cm.getPropertyValues( entity, entityMode );
Type[] types = entityPersister.getPropertyTypes();
String[] names = entityPersister.getPropertyNames();
Object[] values = entityPersister.getPropertyValues( entity );
for ( int i=0; i<types.length; i++ ) {
if ( !names[i].startsWith("_") ) {
String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ?
@ -78,38 +80,42 @@ public final class Printer {
result.put( names[i], strValue );
}
}
return cm.getEntityName() + result.toString();
return entityPersister.getEntityName() + result.toString();
}
public String toString(Type[] types, Object[] values) throws HibernateException {
List list = new ArrayList( types.length * 5 );
StringBuilder buffer = new StringBuilder();
for ( int i=0; i<types.length; i++ ) {
if ( types[i]!=null ) list.add( types[i].toLoggableString( values[i], factory ) );
if ( types[i]!=null ) {
buffer.append( types[i].toLoggableString( values[i], factory ) ).append( ", " );
}
}
return list.toString();
return buffer.toString();
}
public String toString(Map namedTypedValues) throws HibernateException {
Map result = new HashMap();
Iterator iter = namedTypedValues.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = (Map.Entry) iter.next();
TypedValue tv = (TypedValue) me.getValue();
result.put( me.getKey(), tv.getType().toLoggableString( tv.getValue(), factory ) );
public String toString(Map<String,TypedValue> namedTypedValues) throws HibernateException {
Map<String,String> result = new HashMap<String,String>();
for ( Map.Entry<String, TypedValue> entry : namedTypedValues.entrySet() ) {
result.put(
entry.getKey(), entry.getValue().getType().toLoggableString(
entry.getValue().getValue(),
factory
)
);
}
return result.toString();
}
public void toString(Iterator iter, EntityMode entityMode) throws HibernateException {
if (!LOG.isDebugEnabled() || !iter.hasNext()) return;
LOG.debugf("Listing entities:");
public void toString(Iterator iterator) throws HibernateException {
if (!LOG.isDebugEnabled() || !iterator.hasNext()) return;
LOG.debugf( "Listing entities:" );
int i=0;
while ( iter.hasNext() ) {
while ( iterator.hasNext() ) {
if (i++>20) {
LOG.debugf("More......");
break;
}
LOG.debugf(toString(iter.next(), entityMode));
LOG.debugf( toString( iterator.next() ) );
}
}

View File

@ -1,401 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
* third-party contributors as indicated by either @author tags or express
* copyright attribution statements applied by the authors. All
* third-party contributions are distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.property;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.Node;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.PropertyNotFoundException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.CollectionType;
import org.hibernate.type.Type;
/**
* Responsible for accessing property values represented as a dom4j Element
* or Attribute.
*
* @author Steve Ebersole
*/
public class Dom4jAccessor implements PropertyAccessor {
private String nodeName;
private Type propertyType;
private final SessionFactoryImplementor factory;
public Dom4jAccessor(String nodeName, Type propertyType, SessionFactoryImplementor factory) {
this.factory = factory;
this.nodeName = nodeName;
this.propertyType = propertyType;
}
/**
* Create a "getter" for the named attribute
*/
public Getter getGetter(Class theClass, String propertyName)
throws PropertyNotFoundException {
if (nodeName==null) {
throw new MappingException("no node name for property: " + propertyName);
}
if ( ".".equals(nodeName) ) {
return new TextGetter(propertyType, factory);
}
else if ( nodeName.indexOf('/')>-1 ) {
return new ElementAttributeGetter(nodeName, propertyType, factory);
}
else if ( nodeName.indexOf('@')>-1 ) {
return new AttributeGetter(nodeName, propertyType, factory);
}
else {
return new ElementGetter(nodeName, propertyType, factory);
}
}
/**
* Create a "setter" for the named attribute
*/
public Setter getSetter(Class theClass, String propertyName)
throws PropertyNotFoundException {
if (nodeName==null) {
throw new MappingException("no node name for property: " + propertyName);
}
if ( ".".equals(nodeName) ) {
return new TextSetter(propertyType);
}
else if ( nodeName.indexOf('/')>-1 ) {
return new ElementAttributeSetter(nodeName, propertyType);
}
else if ( nodeName.indexOf('@')>-1 ) {
return new AttributeSetter(nodeName, propertyType);
}
else {
return new ElementSetter(nodeName, propertyType);
}
}
/**
* Defines the strategy for getting property values out of a dom4j Node.
*/
public abstract static class Dom4jGetter implements Getter {
protected final Type propertyType;
protected final SessionFactoryImplementor factory;
Dom4jGetter(Type propertyType, SessionFactoryImplementor factory) {
this.propertyType = propertyType;
this.factory = factory;
}
public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session)
throws HibernateException {
return get( owner );
}
/**
* {@inheritDoc}
*/
public Class getReturnType() {
return Object.class;
}
/**
* {@inheritDoc}
*/
public Member getMember() {
return null;
}
/**
* {@inheritDoc}
*/
public String getMethodName() {
return null;
}
/**
* {@inheritDoc}
*/
public Method getMethod() {
return null;
}
}
public abstract static class Dom4jSetter implements Setter {
protected final Type propertyType;
Dom4jSetter(Type propertyType) {
this.propertyType = propertyType;
}
/**
* {@inheritDoc}
*/
public String getMethodName() {
return null;
}
/**
* {@inheritDoc}
*/
public Method getMethod() {
return null;
}
}
/**
* For nodes like <tt>"."</tt>
* @author Gavin King
*/
public static class TextGetter extends Dom4jGetter {
TextGetter(Type propertyType, SessionFactoryImplementor factory) {
super(propertyType, factory);
}
/**
* {@inheritDoc}
*/
public Object get(Object owner) throws HibernateException {
Element ownerElement = (Element) owner;
return super.propertyType.fromXMLNode(ownerElement, super.factory);
}
}
/**
* For nodes like <tt>"@bar"</tt>
* @author Gavin King
*/
public static class AttributeGetter extends Dom4jGetter {
private final String attributeName;
AttributeGetter(String name, Type propertyType, SessionFactoryImplementor factory) {
super(propertyType, factory);
attributeName = name.substring(1);
}
/**
* {@inheritDoc}
*/
public Object get(Object owner) throws HibernateException {
Element ownerElement = (Element) owner;
Node attribute = ownerElement.attribute(attributeName);
return attribute==null ? null :
super.propertyType.fromXMLNode(attribute, super.factory);
}
}
/**
* For nodes like <tt>"foo"</tt>
* @author Gavin King
*/
public static class ElementGetter extends Dom4jGetter {
private final String elementName;
ElementGetter(String name, Type propertyType, SessionFactoryImplementor factory) {
super(propertyType, factory);
elementName = name;
}
/**
* {@inheritDoc}
*/
public Object get(Object owner) throws HibernateException {
Element ownerElement = (Element) owner;
Node element = ownerElement.element(elementName);
return element==null ?
null : super.propertyType.fromXMLNode(element, super.factory);
}
}
/**
* For nodes like <tt>"foo/@bar"</tt>
* @author Gavin King
*/
public static class ElementAttributeGetter extends Dom4jGetter {
private final String elementName;
private final String attributeName;
ElementAttributeGetter(String name, Type propertyType, SessionFactoryImplementor factory) {
super(propertyType, factory);
elementName = name.substring( 0, name.indexOf('/') );
attributeName = name.substring( name.indexOf('/')+2 );
}
/**
* {@inheritDoc}
*/
public Object get(Object owner) throws HibernateException {
Element ownerElement = (Element) owner;
Element element = ownerElement.element(elementName);
if ( element==null ) {
return null;
}
else {
Attribute attribute = element.attribute(attributeName);
if (attribute==null) {
return null;
}
else {
return super.propertyType.fromXMLNode(attribute, super.factory);
}
}
}
}
/**
* For nodes like <tt>"."</tt>
* @author Gavin King
*/
public static class TextSetter extends Dom4jSetter {
TextSetter(Type propertyType) {
super(propertyType);
}
/**
* {@inheritDoc}
*/
public void set(Object target, Object value, SessionFactoryImplementor factory)
throws HibernateException {
Element owner = ( Element ) target;
if ( !super.propertyType.isXMLElement() ) { //kinda ugly, but needed for collections with a "." node mapping
if (value==null) {
owner.setText(null); //is this ok?
}
else {
super.propertyType.setToXMLNode(owner, value, factory);
}
}
}
}
/**
* For nodes like <tt>"@bar"</tt>
* @author Gavin King
*/
public static class AttributeSetter extends Dom4jSetter {
private final String attributeName;
AttributeSetter(String name, Type propertyType) {
super(propertyType);
attributeName = name.substring(1);
}
/**
* {@inheritDoc}
*/
public void set(Object target, Object value, SessionFactoryImplementor factory)
throws HibernateException {
Element owner = ( Element ) target;
Attribute attribute = owner.attribute(attributeName);
if (value==null) {
if (attribute!=null) attribute.detach();
}
else {
if (attribute==null) {
owner.addAttribute(attributeName, "null");
attribute = owner.attribute(attributeName);
}
super.propertyType.setToXMLNode(attribute, value, factory);
}
}
}
/**
* For nodes like <tt>"foo"</tt>
* @author Gavin King
*/
public static class ElementSetter extends Dom4jSetter {
private final String elementName;
ElementSetter(String name, Type propertyType) {
super(propertyType);
elementName = name;
}
/**
* {@inheritDoc}
*/
public void set(Object target, Object value, SessionFactoryImplementor factory)
throws HibernateException {
if (value!=CollectionType.UNFETCHED_COLLECTION) {
Element owner = ( Element ) target;
Element existing = owner.element(elementName);
if (existing!=null) existing.detach();
if (value!=null) {
Element element = owner.addElement(elementName);
super.propertyType.setToXMLNode(element, value, factory);
}
}
}
}
/**
* For nodes like <tt>"foo/@bar"</tt>
* @author Gavin King
*/
public static class ElementAttributeSetter extends Dom4jSetter {
private final String elementName;
private final String attributeName;
ElementAttributeSetter(String name, Type propertyType) {
super(propertyType);
elementName = name.substring( 0, name.indexOf('/') );
attributeName = name.substring( name.indexOf('/')+2 );
}
/**
* {@inheritDoc}
*/
public void set(Object target, Object value, SessionFactoryImplementor factory)
throws HibernateException {
Element owner = ( Element ) target;
Element element = owner.element(elementName);
if (value==null) {
if (element!=null) element.detach();
}
else {
Attribute attribute;
if (element==null) {
element = owner.addElement(elementName);
attribute = null;
}
else {
attribute = element.attribute(attributeName);
}
if (attribute==null) {
element.addAttribute(attributeName, "null");
attribute = element.attribute(attributeName);
}
super.propertyType.setToXMLNode(attribute, value, factory);
}
}
}
}

View File

@ -76,11 +76,6 @@ public final class PropertyAccessorFactory {
else if ( EntityMode.MAP.equals( mode ) ) {
return getDynamicMapPropertyAccessor();
}
else if ( EntityMode.DOM4J.equals( mode ) ) {
//TODO: passing null here, because this method is not really used for DOM4J at the moment
// but it is still a bug, if we don't get rid of this!
return getDom4jPropertyAccessor( property.getAccessorPropertyName( mode ), property.getType(), null );
}
else {
throw new MappingException( "Unknown entity mode [" + mode + "]" );
}
@ -112,13 +107,6 @@ public final class PropertyAccessorFactory {
return MAP_ACCESSOR;
}
public static PropertyAccessor getDom4jPropertyAccessor(String nodeName, Type type, SessionFactoryImplementor factory)
throws MappingException {
//TODO: need some caching scheme? really comes down to decision
// regarding amount of state (if any) kept on PropertyAccessors
return new Dom4jAccessor( nodeName, type, factory );
}
private static PropertyAccessor resolveCustomAccessor(String accessorName) {
Class accessorClass;
try {

View File

@ -1,104 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.tuple;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
/**
* Centralizes handling of {@link EntityMode} to {@link Tuplizer} mappings.
*
* @author Steve Ebersole
*/
public abstract class EntityModeToTuplizerMapping implements Serializable {
private final Map<EntityMode,Tuplizer> tuplizers;
public EntityModeToTuplizerMapping() {
tuplizers = new ConcurrentHashMap<EntityMode,Tuplizer>();
}
@SuppressWarnings({ "unchecked", "UnusedDeclaration" })
public EntityModeToTuplizerMapping(Map tuplizers) {
this.tuplizers = tuplizers;
}
protected void addTuplizer(EntityMode entityMode, Tuplizer tuplizer) {
tuplizers.put( entityMode, tuplizer );
}
/**
* Allow iteration over all defined {@link Tuplizer Tuplizers}.
*
* @return Iterator over defined tuplizers
*/
public Iterator iterateTuplizers() {
return tuplizers.values().iterator();
}
/**
* Given a supposed instance of an entity/component, guess its entity mode.
*
* @param object The supposed instance of the entity/component.
* @return The guessed entity mode.
*/
public EntityMode guessEntityMode(Object object) {
for ( Map.Entry<EntityMode, Tuplizer> entityModeTuplizerEntry : tuplizers.entrySet() ) {
if ( entityModeTuplizerEntry.getValue().isInstance( object ) ) {
return entityModeTuplizerEntry.getKey();
}
}
return null;
}
/**
* Locate the contained tuplizer responsible for the given entity-mode. If
* no such tuplizer is defined on this mapping, then return null.
*
* @param entityMode The entity-mode for which the caller wants a tuplizer.
* @return The tuplizer, or null if not found.
*/
public Tuplizer getTuplizerOrNull(EntityMode entityMode) {
return tuplizers.get( entityMode );
}
/**
* Locate the tuplizer contained within this mapping which is responsible
* for the given entity-mode. If no such tuplizer is defined on this
* mapping, then an exception is thrown.
*
* @param entityMode The entity-mode for which the caller wants a tuplizer.
* @return The tuplizer.
* @throws HibernateException Unable to locate the requested tuplizer.
*/
public Tuplizer getTuplizer(EntityMode entityMode) {
Tuplizer tuplizer = getTuplizerOrNull( entityMode );
if ( tuplizer == null ) {
throw new HibernateException( "No tuplizer found for entity-mode [" + entityMode + "]");
}
return tuplizer;
}
}

View File

@ -1,121 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* 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
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.tuple.component;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.tuple.EntityModeToTuplizerMapping;
import org.hibernate.tuple.Tuplizer;
/**
* Handles mapping {@link EntityMode}s to {@link ComponentTuplizer}s.
* <p/>
* Most of the handling is really in the super class; here we just create
* the tuplizers and add them to the superclass
*
* @author Steve Ebersole
*/
class ComponentEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
// todo : move this to SF per HHH-3517; also see HHH-1907 and ComponentMetamodel
private ComponentTuplizerFactory componentTuplizerFactory = new ComponentTuplizerFactory();
public ComponentEntityModeToTuplizerMapping(Component component) {
PersistentClass owner = component.getOwner();
// create our own copy of the user-supplied tuplizer impl map
Map userSuppliedTuplizerImpls = new HashMap();
if ( component.getTuplizerMap() != null ) {
userSuppliedTuplizerImpls.putAll( component.getTuplizerMap() );
}
// Build the dynamic-map tuplizer...
Tuplizer dynamicMapTuplizer;
String tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
if ( tuplizerClassName == null ) {
dynamicMapTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, component );
}
else {
dynamicMapTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
Tuplizer pojoTuplizer;
if ( owner.hasPojoRepresentation() && component.hasPojoRepresentation() ) {
if ( tuplizerClassName == null ) {
pojoTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, component );
}
else {
pojoTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
pojoTuplizer = dynamicMapTuplizer;
}
// then dom4j tuplizer, if dom4j representation is available
Tuplizer dom4jTuplizer;
tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( owner.hasDom4jRepresentation() ) {
if ( tuplizerClassName == null ) {
dom4jTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, component );
}
else {
dom4jTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
dom4jTuplizer = null;
}
// put the "standard" tuplizers into the tuplizer map first
if ( pojoTuplizer != null ) {
addTuplizer( EntityMode.POJO, pojoTuplizer );
}
if ( dynamicMapTuplizer != null ) {
addTuplizer( EntityMode.MAP, dynamicMapTuplizer );
}
if ( dom4jTuplizer != null ) {
addTuplizer( EntityMode.DOM4J, dom4jTuplizer );
}
// then handle any user-defined entity modes...
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
final Map.Entry entry = ( Map.Entry ) itr.next();
final EntityMode entityMode = ( EntityMode ) entry.getKey();
final String userTuplizerClassName = ( String ) entry.getValue();
ComponentTuplizer tuplizer = componentTuplizerFactory.constructTuplizer( userTuplizerClassName, component );
addTuplizer( entityMode, tuplizer );
}
}
}
}

View File

@ -1,109 +1,128 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* 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
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.tuple.component;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.Property;
import org.hibernate.tuple.PropertyFactory;
import org.hibernate.tuple.StandardProperty;
/**
* Centralizes metamodel information about a component.
*
* @author Steve Ebersole
*/
public class ComponentMetamodel implements Serializable {
// TODO : will need reference to session factory to fully complete HHH-1907
// private final SessionFactoryImplementor sessionFactory;
private final String role;
private final boolean isKey;
private final StandardProperty[] properties;
private final ComponentEntityModeToTuplizerMapping tuplizerMapping;
// cached for efficiency...
private final int propertySpan;
private final Map propertyIndexes = new HashMap();
// public ComponentMetamodel(Component component, SessionFactoryImplementor sessionFactory) {
public ComponentMetamodel(Component component) {
// this.sessionFactory = sessionFactory;
this.role = component.getRoleName();
this.isKey = component.isKey();
propertySpan = component.getPropertySpan();
properties = new StandardProperty[propertySpan];
Iterator itr = component.getPropertyIterator();
int i = 0;
while ( itr.hasNext() ) {
Property property = ( Property ) itr.next();
properties[i] = PropertyFactory.buildStandardProperty( property, false );
propertyIndexes.put( property.getName(), i );
i++;
}
tuplizerMapping = new ComponentEntityModeToTuplizerMapping( component );
}
public boolean isKey() {
return isKey;
}
public int getPropertySpan() {
return propertySpan;
}
public StandardProperty[] getProperties() {
return properties;
}
public StandardProperty getProperty(int index) {
if ( index < 0 || index >= propertySpan ) {
throw new IllegalArgumentException( "illegal index value for component property access [request=" + index + ", span=" + propertySpan + "]" );
}
return properties[index];
}
public int getPropertyIndex(String propertyName) {
Integer index = ( Integer ) propertyIndexes.get( propertyName );
if ( index == null ) {
throw new HibernateException( "component does not contain such a property [" + propertyName + "]" );
}
return index.intValue();
}
public StandardProperty getProperty(String propertyName) {
return getProperty( getPropertyIndex( propertyName ) );
}
public ComponentEntityModeToTuplizerMapping getTuplizerMapping() {
return tuplizerMapping;
}
}
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* 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
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.tuple.component;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.Property;
import org.hibernate.tuple.PropertyFactory;
import org.hibernate.tuple.StandardProperty;
import org.hibernate.tuple.Tuplizer;
/**
* Centralizes metamodel information about a component.
*
* @author Steve Ebersole
*/
public class ComponentMetamodel implements Serializable {
// TODO : will need reference to session factory to fully complete HHH-1907
// private final SessionFactoryImplementor sessionFactory;
private final String role;
private final boolean isKey;
private final StandardProperty[] properties;
private final EntityMode entityMode;
private final ComponentTuplizer componentTuplizer;
// cached for efficiency...
private final int propertySpan;
private final Map propertyIndexes = new HashMap();
// public ComponentMetamodel(Component component, SessionFactoryImplementor sessionFactory) {
public ComponentMetamodel(Component component) {
// this.sessionFactory = sessionFactory;
this.role = component.getRoleName();
this.isKey = component.isKey();
propertySpan = component.getPropertySpan();
properties = new StandardProperty[propertySpan];
Iterator itr = component.getPropertyIterator();
int i = 0;
while ( itr.hasNext() ) {
Property property = ( Property ) itr.next();
properties[i] = PropertyFactory.buildStandardProperty( property, false );
propertyIndexes.put( property.getName(), i );
i++;
}
entityMode = component.hasPojoRepresentation() ? EntityMode.POJO : EntityMode.MAP;
// todo : move this to SF per HHH-3517; also see HHH-1907 and ComponentMetamodel
final ComponentTuplizerFactory componentTuplizerFactory = new ComponentTuplizerFactory();
final String tuplizerClassName = component.getTuplizerImplClassName( entityMode );
if ( tuplizerClassName == null ) {
componentTuplizer = componentTuplizerFactory.constructDefaultTuplizer( entityMode, component );
}
else {
componentTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
public boolean isKey() {
return isKey;
}
public int getPropertySpan() {
return propertySpan;
}
public StandardProperty[] getProperties() {
return properties;
}
public StandardProperty getProperty(int index) {
if ( index < 0 || index >= propertySpan ) {
throw new IllegalArgumentException( "illegal index value for component property access [request=" + index + ", span=" + propertySpan + "]" );
}
return properties[index];
}
public int getPropertyIndex(String propertyName) {
Integer index = ( Integer ) propertyIndexes.get( propertyName );
if ( index == null ) {
throw new HibernateException( "component does not contain such a property [" + propertyName + "]" );
}
return index.intValue();
}
public StandardProperty getProperty(String propertyName) {
return getProperty( getPropertyIndex( propertyName ) );
}
public EntityMode getEntityMode() {
return entityMode;
}
public ComponentTuplizer getComponentTuplizer() {
return componentTuplizer;
}
}

View File

@ -153,7 +153,6 @@ public class ComponentTuplizerFactory implements Serializable {
private static Map<EntityMode,Class<? extends ComponentTuplizer>> buildBaseMapping() {
Map<EntityMode,Class<? extends ComponentTuplizer>> map = new ConcurrentHashMap<EntityMode,Class<? extends ComponentTuplizer>>();
map.put( EntityMode.POJO, PojoComponentTuplizer.class );
map.put( EntityMode.DOM4J, Dom4jComponentTuplizer.class );
map.put( EntityMode.MAP, DynamicMapComponentTuplizer.class );
return map;
}

View File

@ -1,71 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* 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
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.tuple.component;
import org.dom4j.Element;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.Property;
import org.hibernate.property.Getter;
import org.hibernate.property.PropertyAccessor;
import org.hibernate.property.PropertyAccessorFactory;
import org.hibernate.property.Setter;
import org.hibernate.tuple.Dom4jInstantiator;
import org.hibernate.tuple.Instantiator;
/**
* A {@link ComponentTuplizer} specific to the dom4j entity mode.
*
* @author Gavin King
* @author Steve Ebersole
*/
public class Dom4jComponentTuplizer extends AbstractComponentTuplizer {
public Class getMappedClass() {
return Element.class;
}
public Dom4jComponentTuplizer(Component component) {
super(component);
}
protected Instantiator buildInstantiator(Component component) {
return new Dom4jInstantiator( component );
}
private PropertyAccessor buildPropertyAccessor(Property property) {
//TODO: currently we don't know a SessionFactory reference when building the Tuplizer
// THIS IS A BUG (embedded-xml=false on component)
// TODO : fix this after HHH-1907 is complete
return PropertyAccessorFactory.getDom4jPropertyAccessor( property.getNodeName(), property.getType(), null );
}
protected Getter buildGetter(Component component, Property prop) {
return buildPropertyAccessor(prop).getGetter( null, prop.getName() );
}
protected Setter buildSetter(Component component, Property prop) {
return buildPropertyAccessor(prop).getSetter( null, prop.getName() );
}
}

View File

@ -425,7 +425,7 @@ public abstract class AbstractEntityTuplizer implements EntityTuplizer {
injectionValues[i] = extractedValues[i];
}
}
virtualIdComponent.setPropertyValues( entity, injectionValues, session.getEntityMode() );
virtualIdComponent.setPropertyValues( entity, injectionValues, entityMode );
}
}

View File

@ -1,239 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.tuple.entity;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Element;
import org.hibernate.EntityMode;
import org.hibernate.EntityNameResolver;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.property.Getter;
import org.hibernate.property.PropertyAccessor;
import org.hibernate.property.PropertyAccessorFactory;
import org.hibernate.property.Setter;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.ProxyFactory;
import org.hibernate.proxy.dom4j.Dom4jProxyFactory;
import org.hibernate.tuple.Dom4jInstantiator;
import org.hibernate.tuple.Instantiator;
import org.hibernate.type.CompositeType;
import org.jboss.logging.Logger;
/**
* An {@link EntityTuplizer} specific to the dom4j entity mode.
*
* @author Steve Ebersole
* @author Gavin King
*/
public class Dom4jEntityTuplizer extends AbstractEntityTuplizer {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Dom4jEntityTuplizer.class.getName());
private Map inheritenceNodeNameMap = new HashMap();
Dom4jEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
super( entityMetamodel, mappedEntity );
inheritenceNodeNameMap.put( mappedEntity.getNodeName(), mappedEntity.getEntityName() );
Iterator itr = mappedEntity.getSubclassClosureIterator();
while( itr.hasNext() ) {
final PersistentClass mapping = ( PersistentClass ) itr.next();
inheritenceNodeNameMap.put( mapping.getNodeName(), mapping.getEntityName() );
}
}
/**
* {@inheritDoc}
*/
public EntityMode getEntityMode() {
return EntityMode.DOM4J;
}
private PropertyAccessor buildPropertyAccessor(Property mappedProperty) {
if ( mappedProperty.isBackRef() ) {
return mappedProperty.getPropertyAccessor(null);
}
else {
return PropertyAccessorFactory.getDom4jPropertyAccessor(
mappedProperty.getNodeName(),
mappedProperty.getType(),
getEntityMetamodel().getSessionFactory()
);
}
}
/**
* {@inheritDoc}
*/
@Override
protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) {
return buildPropertyAccessor(mappedProperty).getGetter( null, mappedProperty.getName() );
}
/**
* {@inheritDoc}
*/
@Override
protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) {
return buildPropertyAccessor(mappedProperty).getSetter( null, mappedProperty.getName() );
}
/**
* {@inheritDoc}
*/
@Override
protected Instantiator buildInstantiator(PersistentClass persistentClass) {
return new Dom4jInstantiator( persistentClass );
}
/**
* {@inheritDoc}
*/
@Override
public Serializable getIdentifier(Object entityOrId) throws HibernateException {
return getIdentifier( entityOrId, null );
}
/**
* {@inheritDoc}
*/
@Override
public Serializable getIdentifier(Object entityOrId, SessionImplementor session) {
if ( entityOrId instanceof Element ) {
return super.getIdentifier( entityOrId, session );
}
else {
//it was not embedded, so the argument is just an id
return (Serializable) entityOrId;
}
}
/**
* {@inheritDoc}
*/
@Override
protected ProxyFactory buildProxyFactory(PersistentClass mappingInfo, Getter idGetter, Setter idSetter) {
HashSet proxyInterfaces = new HashSet();
proxyInterfaces.add( HibernateProxy.class );
proxyInterfaces.add( Element.class );
ProxyFactory pf = new Dom4jProxyFactory();
try {
pf.postInstantiate(
getEntityName(),
Element.class,
proxyInterfaces,
null,
null,
mappingInfo.hasEmbeddedIdentifier() ?
(CompositeType) mappingInfo.getIdentifier().getType() :
null
);
}
catch ( HibernateException he ) {
LOG.unableToCreateProxyFactory(getEntityName(), he);
pf = null;
}
return pf;
}
/**
* {@inheritDoc}
*/
public Class getMappedClass() {
return Element.class;
}
/**
* {@inheritDoc}
*/
public Class getConcreteProxyClass() {
return Element.class;
}
/**
* {@inheritDoc}
*/
public boolean isInstrumented() {
return false;
}
/**
* {@inheritDoc}
*/
public EntityNameResolver[] getEntityNameResolvers() {
return new EntityNameResolver[] { new BasicEntityNameResolver( getEntityName(), inheritenceNodeNameMap ) };
}
/**
* {@inheritDoc}
*/
public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory) {
return ( String ) inheritenceNodeNameMap.get( extractNodeName( ( Element ) entityInstance ) );
}
public static String extractNodeName(Element element) {
return element.getName();
}
public static class BasicEntityNameResolver implements EntityNameResolver {
private final String rootEntityName;
private final Map nodeNameToEntityNameMap;
public BasicEntityNameResolver(String rootEntityName, Map nodeNameToEntityNameMap) {
this.rootEntityName = rootEntityName;
this.nodeNameToEntityNameMap = nodeNameToEntityNameMap;
}
/**
* {@inheritDoc}
*/
public String resolveEntityName(Object entity) {
return ( String ) nodeNameToEntityNameMap.get( extractNodeName( ( Element ) entity ) );
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
return rootEntityName.equals( ( ( BasicEntityNameResolver ) obj ).rootEntityName );
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return rootEntityName.hashCode();
}
}
}

View File

@ -166,6 +166,9 @@ public class DynamicMapEntityTuplizer extends AbstractEntityTuplizer {
* {@inheritDoc}
*/
public String resolveEntityName(Object entity) {
if ( ! Map.class.isInstance( entity ) ) {
return null;
}
final String entityName = extractEmbeddedEntityName( ( Map ) entity );
if ( entityName == null ) {
throw new HibernateException( "Could not determine type of dynamic map entity" );

View File

@ -1,126 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* 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
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.tuple.entity;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.hibernate.EntityMode;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.tuple.EntityModeToTuplizerMapping;
import org.hibernate.tuple.Tuplizer;
/**
* Handles mapping {@link EntityMode}s to {@link EntityTuplizer}s.
* <p/>
* Most of the handling is really in the super class; here we just create
* the tuplizers and add them to the superclass
*
* @author Steve Ebersole
*/
public class EntityEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
/**
* Instantiates a EntityEntityModeToTuplizerMapping based on the given
* entity mapping and metamodel definitions.
*
* @param mappedEntity The entity mapping definition.
* @param em The entity metamodel definition.
*/
public EntityEntityModeToTuplizerMapping(PersistentClass mappedEntity, EntityMetamodel em) {
final EntityTuplizerFactory entityTuplizerFactory = em.getSessionFactory()
.getSettings()
.getEntityTuplizerFactory();
// create our own copy of the user-supplied tuplizer impl map
Map userSuppliedTuplizerImpls = new HashMap();
if ( mappedEntity.getTuplizerMap() != null ) {
userSuppliedTuplizerImpls.putAll( mappedEntity.getTuplizerMap() );
}
// Build the dynamic-map tuplizer...
Tuplizer dynamicMapTuplizer;
String tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
if ( tuplizerImplClassName == null ) {
dynamicMapTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, em, mappedEntity );
}
else {
dynamicMapTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
Tuplizer pojoTuplizer;
tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
if ( mappedEntity.hasPojoRepresentation() ) {
if ( tuplizerImplClassName == null ) {
pojoTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, em, mappedEntity );
}
else {
pojoTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
pojoTuplizer = dynamicMapTuplizer;
}
// then dom4j tuplizer, if dom4j representation is available
Tuplizer dom4jTuplizer;
tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( mappedEntity.hasDom4jRepresentation() ) {
if ( tuplizerImplClassName == null ) {
dom4jTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, em, mappedEntity );
}
else {
dom4jTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
dom4jTuplizer = null;
}
// put the "standard" tuplizers into the tuplizer map first
if ( pojoTuplizer != null ) {
addTuplizer( EntityMode.POJO, pojoTuplizer );
}
if ( dynamicMapTuplizer != null ) {
addTuplizer( EntityMode.MAP, dynamicMapTuplizer );
}
if ( dom4jTuplizer != null ) {
addTuplizer( EntityMode.DOM4J, dom4jTuplizer );
}
// then handle any user-defined entity modes...
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
final Map.Entry entry = ( Map.Entry ) itr.next();
final EntityMode entityMode = ( EntityMode ) entry.getKey();
final String tuplizerClassName = ( String ) entry.getValue();
final EntityTuplizer tuplizer = entityTuplizerFactory.constructTuplizer( tuplizerClassName, em, mappedEntity );
addTuplizer( entityMode, tuplizer );
}
}
}
}

View File

@ -31,15 +31,18 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.bytecode.instrumentation.internal.FieldInterceptionHelper;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.CascadeStyle;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.ValueInclusion;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.bytecode.instrumentation.internal.FieldInterceptionHelper;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.mapping.Component;
@ -54,7 +57,6 @@ import org.hibernate.type.AssociationType;
import org.hibernate.type.CompositeType;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Centralizes metamodel information about an entity.
@ -121,7 +123,8 @@ public class EntityMetamodel implements Serializable {
private final Set subclassEntityNames = new HashSet();
private final Map entityNameByInheritenceClassMap = new HashMap();
private final EntityEntityModeToTuplizerMapping tuplizerMapping;
private final EntityMode entityMode;
private final EntityTuplizer entityTuplizer;
public EntityMetamodel(PersistentClass persistentClass, SessionFactoryImplementor sessionFactory) {
this.sessionFactory = sessionFactory;
@ -315,7 +318,15 @@ public class EntityMetamodel implements Serializable {
}
}
tuplizerMapping = new EntityEntityModeToTuplizerMapping( persistentClass, this );
entityMode = persistentClass.hasPojoRepresentation() ? EntityMode.POJO : EntityMode.MAP;
final EntityTuplizerFactory entityTuplizerFactory = sessionFactory.getSettings().getEntityTuplizerFactory();
final String tuplizerClassName = persistentClass.getTuplizerImplClassName( entityMode );
if ( tuplizerClassName == null ) {
entityTuplizer = entityTuplizerFactory.constructDefaultTuplizer( entityMode, this, persistentClass );
}
else {
entityTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerClassName, this, persistentClass );
}
}
private ValueInclusion determineInsertValueGenerationType(Property mappingProperty, StandardProperty runtimeProperty) {
@ -388,20 +399,8 @@ public class EntityMetamodel implements Serializable {
}
}
public EntityEntityModeToTuplizerMapping getTuplizerMapping() {
return tuplizerMapping;
}
public EntityTuplizer getTuplizer(EntityMode entityMode) {
return (EntityTuplizer) tuplizerMapping.getTuplizer( entityMode );
}
public EntityTuplizer getTuplizerOrNull(EntityMode entityMode) {
return ( EntityTuplizer ) tuplizerMapping.getTuplizerOrNull( entityMode );
}
public EntityMode guessEntityMode(Object object) {
return tuplizerMapping.guessEntityMode( object );
public EntityTuplizer getTuplizer() {
return entityTuplizer;
}
public int[] getNaturalIdentifierProperties() {
@ -635,4 +634,8 @@ public class EntityMetamodel implements Serializable {
public boolean hasUpdateGeneratedValues() {
return hasUpdateGeneratedValues;
}
public EntityMode getEntityMode() {
return entityMode;
}
}

View File

@ -22,14 +22,16 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.tuple.entity;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.mapping.PersistentClass;
/**
* A registry allowing users to define the default {@link EntityTuplizer} class to use per {@link EntityMode}.
@ -163,7 +165,6 @@ public class EntityTuplizerFactory implements Serializable {
private static Map<EntityMode,Class<? extends EntityTuplizer>> buildBaseMapping() {
Map<EntityMode,Class<? extends EntityTuplizer>> map = new ConcurrentHashMap<EntityMode,Class<? extends EntityTuplizer>>();
map.put( EntityMode.POJO, PojoEntityTuplizer.class );
map.put( EntityMode.DOM4J, Dom4jEntityTuplizer.class );
map.put( EntityMode.MAP, DynamicMapEntityTuplizer.class );
return map;
}

View File

@ -31,7 +31,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Comparator;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionImplementor;
@ -122,16 +122,14 @@ public abstract class AbstractBynaryType extends MutableType implements VersionT
return this;
}
public int compare(Object o1, Object o2) {
return compare( o1, o2, null );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public boolean isEqual(Object x, Object y) {
return x==y || ( x!=null && y!=null && java.util.Arrays.equals( toInternalFormat(x), toInternalFormat(y) ) );
}
public int getHashCode(Object x, EntityMode entityMode) {
public int getHashCode(Object x) {
byte[] bytes = toInternalFormat(x);
int hashCode = 1;
for ( int j=0; j<bytes.length; j++ ) {
@ -140,7 +138,7 @@ public abstract class AbstractBynaryType extends MutableType implements VersionT
return hashCode;
}
public int compare(Object x, Object y, EntityMode entityMode) {
public int compare(Object x, Object y) {
byte[] xbytes = toInternalFormat(x);
byte[] ybytes = toInternalFormat(y);
if ( xbytes.length < ybytes.length ) return -1;

View File

@ -1,118 +1,120 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
/**
* Logic to bind stream of char into a VARCHAR
*
* @author Emmanuel Bernard
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractCharArrayType extends MutableType {
/**
* Convert the char[] into the expected object type
*/
abstract protected Object toExternalFormat(char[] chars);
/**
* Convert the object into the internal char[] representation
*/
abstract protected char[] toInternalFormat(Object chars);
public Object get(ResultSet rs, String name) throws SQLException {
Reader stream = rs.getCharacterStream(name);
if ( stream == null ) return toExternalFormat( null );
CharArrayWriter writer = new CharArrayWriter();
for(;;) {
try {
int c = stream.read();
if ( c == -1) return toExternalFormat( writer.toCharArray() );
writer.write( c );
}
catch (IOException e) {
throw new HibernateException("Unable to read character stream from rs");
}
}
}
public abstract Class getReturnedClass();
public void set(PreparedStatement st, Object value, int index) throws SQLException {
char[] chars = toInternalFormat( value );
st.setCharacterStream(index, new CharArrayReader(chars), chars.length);
}
public int sqlType() {
return Types.VARCHAR;
}
public String objectToSQLString(Object value, Dialect dialect) throws Exception {
return '\'' + new String( toInternalFormat( value ) ) + '\'';
}
public Object stringToObject(String xml) throws Exception {
if (xml == null) return toExternalFormat( null );
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
public String toString(Object value) {
if (value == null) return null;
return new String( toInternalFormat( value ) );
}
public Object fromStringValue(String xml) {
if (xml == null) return null;
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
protected Object deepCopyNotNull(Object value) throws HibernateException {
char[] chars = toInternalFormat(value);
char[] result = new char[chars.length];
System.arraycopy(chars, 0, result, 0, chars.length);
return toExternalFormat(result);
}
}
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
/**
* Logic to bind stream of char into a VARCHAR
*
* @author Emmanuel Bernard
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractCharArrayType extends MutableType {
/**
* Convert the char[] into the expected object type
*/
abstract protected Object toExternalFormat(char[] chars);
/**
* Convert the object into the internal char[] representation
*/
abstract protected char[] toInternalFormat(Object chars);
public Object get(ResultSet rs, String name) throws SQLException {
Reader stream = rs.getCharacterStream(name);
if ( stream == null ) return toExternalFormat( null );
CharArrayWriter writer = new CharArrayWriter();
for(;;) {
try {
int c = stream.read();
if ( c == -1) return toExternalFormat( writer.toCharArray() );
writer.write( c );
}
catch (IOException e) {
throw new HibernateException("Unable to read character stream from rs");
}
}
}
public abstract Class getReturnedClass();
public void set(PreparedStatement st, Object value, int index) throws SQLException {
char[] chars = toInternalFormat( value );
st.setCharacterStream(index, new CharArrayReader(chars), chars.length);
}
public int sqlType() {
return Types.VARCHAR;
}
public String objectToSQLString(Object value, Dialect dialect) throws Exception {
return '\'' + new String( toInternalFormat( value ) ) + '\'';
}
public Object stringToObject(String xml) throws Exception {
if (xml == null) return toExternalFormat( null );
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
public String toString(Object value) {
if (value == null) return null;
return new String( toInternalFormat( value ) );
}
public Object fromStringValue(String xml) {
if (xml == null) return null;
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
protected Object deepCopyNotNull(Object value) throws HibernateException {
char[] chars = toInternalFormat(value);
char[] result = new char[chars.length];
System.arraycopy(chars, 0, result, 0, chars.length);
return toExternalFormat(result);
}
}

View File

@ -26,7 +26,7 @@ import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.Mapping;
@ -41,7 +41,7 @@ import org.hibernate.metamodel.relational.Size;
public abstract class AbstractLobType extends AbstractType implements Serializable {
public boolean isDirty(Object old, Object current, boolean[] checkable, SessionImplementor session)
throws HibernateException {
return checkable[0] ? ! isEqual( old, current, session.getEntityMode() ) : false;
return checkable[0] ? ! isEqual( old, current ) : false;
}
@Override
@ -55,13 +55,13 @@ public abstract class AbstractLobType extends AbstractType implements Serializab
}
@Override
public boolean isEqual(Object x, Object y, EntityMode entityMode) {
return isEqual( x, y, entityMode, null );
public boolean isEqual(Object x, Object y) {
return isEqual( x, y, null );
}
@Override
public int getHashCode(Object x, EntityMode entityMode) {
return getHashCode( x, entityMode, null );
public int getHashCode(Object x) {
return getHashCode( x, null );
}
public String getName() {

Some files were not shown because too many files have changed in this diff Show More