下面列出了怎么用org.hibernate.persister.collection.CollectionPersister的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
final Type elementType = persister.getElementType();
final List sn = (List) getSnapshot();
if ( sn.size()!=this.list.size() ) {
return false;
}
final Iterator itr = list.iterator();
final Iterator snapshotItr = sn.iterator();
while ( itr.hasNext() ) {
if ( elementType.isDirty( itr.next(), snapshotItr.next(), getSession() ) ) {
return false;
}
}
return true;
}
@Override
public Object readFrom(
ResultSet rs,
CollectionPersister persister,
CollectionAliases descriptor,
Object owner) throws HibernateException, SQLException {
final Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
final Object old = identifiers.put(
values.size(),
persister.readIdentifier( rs, descriptor.getSuffixedIdentifierAlias(), getSession() )
);
if ( old == null ) {
//maintain correct duplication if loaded in a cartesian product
values.add( element );
}
return element;
}
public Serializable disassemble(CollectionPersister persister) throws HibernateException {
int length = Array.getLength(array);
Serializable[] result = new Serializable[length];
for ( int i=0; i<length; i++ ) {
result[i] = persister.getElementType().disassemble( Array.get(array,i), getSession(), null );
}
/*int length = tempList.size();
Serializable[] result = new Serializable[length];
for ( int i=0; i<length; i++ ) {
result[i] = persister.getElementType().disassemble( tempList.get(i), session );
}*/
return result;
}
@Override
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
// final int length = (array==null) ? tempList.size() : Array.getLength( array );
final int length = Array.getLength( array );
final Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
for ( int i=0; i<length; i++ ) {
// final Object elt = (array==null) ? tempList.get( i ) : Array.get( array, i );
final Object elt = Array.get( array, i );
try {
Array.set( result, i, persister.getElementType().deepCopy( elt, persister.getFactory() ) );
}
catch (IllegalArgumentException iae) {
LOG.invalidArrayElementType( iae.getMessage() );
throw new HibernateException( "Array element type error", iae );
}
}
return result;
}
@Override
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
final Type elementType = persister.getElementType();
final java.util.Map sn = (java.util.Map) getSnapshot();
if ( sn.size()!=set.size() ) {
return false;
}
else {
for ( Object test : set ) {
final Object oldValue = sn.get( test );
if ( oldValue == null || elementType.isDirty( oldValue, test, getSession() ) ) {
return false;
}
}
return true;
}
}
@Override
public void beforeInitialize(CollectionPersister persister, int anticipatedSize) {
super.beforeInitialize(persister, anticipatedSize);
/*java.util.Set<java.util.Map.Entry<String, org.hibernate.impl.FilterImpl>> e = this.getSession().getLoadQueryInfluencers().getEnabledFilters().entrySet();
for(java.util.Map.Entry<String, org.hibernate.impl.FilterImpl> f : e) {
String params = "";
for(Object p : f.getValue().getParameters().values()) {
if(!"".equals(params)) params += ",";
params += p;
}
try{org.webdsl.logging.Logger.info("enabled: " + f.getKey() + "(" + params + ")");}catch(Exception e2){org.webdsl.logging.Logger.error("EXCEPTION",e2);}
}
try{throw new Exception("beforeInitialize");}catch(Exception e){org.webdsl.logging.Logger.error("EXCEPTION",e);}*/
// The super method just initialized the set, so we need to pass on the owner
if(set != null && set instanceof utils.OwnedSet) {
((utils.OwnedSet)set).setOwner(getOwner());
}
}
@Override
public boolean needsRecreate(CollectionPersister persister) {
// Workaround for situations like HHH-7072. If the collection element is a component that consists entirely
// of nullable properties, we currently have to forcefully recreate the entire collection. See the use
// of hasNotNullableColumns in the AbstractCollectionPersister constructor for more info. In order to delete
// row-by-row, that would require SQL like "WHERE ( COL = ? OR ( COL is null AND ? is null ) )", rather than
// the current "WHERE COL = ?" (fails for null for most DBs). Note that
// the param would have to be bound twice. Until we eventually add "parameter bind points" concepts to the
// AST in ORM 5+, handling this type of condition is either extremely difficult or impossible. Forcing
// recreation isn't ideal, but not really any other option in ORM 4.
// Selecting a type used in where part of update statement
// (must match condidion in org.hibernate.persister.collection.BasicCollectionPersister.doUpdateRows).
// See HHH-9474
Type whereType;
if ( persister.hasIndex() ) {
whereType = persister.getIndexType();
}
else {
whereType = persister.getElementType();
}
if ( whereType instanceof CompositeType ) {
CompositeType componentIndexType = (CompositeType) whereType;
return !componentIndexType.hasNotNullProperty();
}
return false;
}
@Override
@SuppressWarnings("unchecked")
public Object readFrom(
ResultSet rs,
CollectionPersister persister,
CollectionAliases descriptor,
Object owner) throws HibernateException, SQLException {
final Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
if ( element != null ) {
final Object index = persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() );
if ( loadingEntries == null ) {
loadingEntries = new ArrayList<>();
}
loadingEntries.add( new Object[] { index, element } );
}
return element;
}
@Override
public Object replaceElements(
final Object original,
final Object target,
final Object owner,
final java.util.Map copyCache,
final SharedSessionContractImplementor session) throws HibernateException {
CollectionPersister cp = session.getFactory().getMetamodel().collectionPersister( getRole() );
java.util.Map result = (java.util.Map) target;
result.clear();
for ( Object o : ( (Map) original ).entrySet() ) {
Map.Entry me = (Map.Entry) o;
Object key = cp.getIndexType().replace( me.getKey(), null, session, owner, copyCache );
Object value = cp.getElementType().replace( me.getValue(), null, session, owner, copyCache );
result.put( key, value );
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner)
throws HibernateException, SQLException {
// note that if we load this collection from a cartesian product
// the multiplicity would be broken ... so use an idbag instead
final Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ) ;
if ( element != null ) {
bag.add( element );
}
return element;
}
public CollectionPersister getCollectionPersister(String role) throws MappingException {
CollectionPersister result = (CollectionPersister) collectionPersisters.get(role);
if (result==null) {
throw new MappingException( "Unknown collection role: " + role );
}
return result;
}
private void endCollectionLoad(
final Object resultSetId,
final SessionImplementor session,
final CollectionPersister collectionPersister) {
//this is a query and we are loading multiple instances of the same collection role
session.getPersistenceContext()
.getLoadContexts()
.getCollectionLoadContext( ( ResultSet ) resultSetId )
.endLoadingCollections( collectionPersister );
}
public void preInsert(CollectionPersister persister) throws HibernateException {
Iterator iter = values.iterator();
int i=0;
while ( iter.hasNext() ) {
Object entry = iter.next();
Integer loc = new Integer(i++);
if ( !identifiers.containsKey(loc) ) { //TODO: native ids
Serializable id = persister.getIdentifierGenerator().generate( getSession(), entry );
identifiers.put(loc, id);
}
}
}
@Override
@SuppressWarnings("unchecked")
public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner)
throws HibernateException {
final Serializable[] array = (Serializable[]) disassembled;
final int size = array.length;
beforeInitialize( persister, size );
for ( int i = 0; i < size; i+=2 ) {
map.put(
persister.getIndexType().assemble( array[i], getSession(), owner ),
persister.getElementType().assemble( array[i+1], getSession(), owner )
);
}
}
public PersistentCollection instantiate(
SessionImplementor session,
CollectionPersister persister, Serializable key)
throws HibernateException {
return new PersistentIdentifierBag(session);
}
private boolean isFoundInParent(
String property,
Object childEntity,
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent) {
final Object collection = persister.getPropertyValue( potentialParent, property );
return collection != null
&& Hibernate.isInitialized( collection )
&& collectionPersister.getCollectionType().contains( collection, childEntity, session );
}
public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner)
throws HibernateException {
Serializable[] array = ( Serializable[] ) disassembled;
int size = array.length;
beforeInitialize( persister, size );
for ( int i = 0; i < size; i++ ) {
list.add( persister.getElementType().assemble( array[i], getSession(), owner ) );
}
}
@Override
public Object replaceElements(Object original, Object target,
CollectionPersister persister, Object owner, Map copyCache,
SessionImplementor session) throws HibernateException {
java.util.Set result = (java.util.Set) target;
result.clear();
result.addAll((java.util.Set) original);
return result;
}
/**
* Replace the elements of a collection with the elements of another collection
*/
Object replaceElements(
Object original,
Object target,
CollectionPersister persister,
Object owner,
Map copyCache,
SharedSessionContractImplementor session) throws HibernateException;
public Object readFrom(
ResultSet rs,
CollectionPersister persister,
CollectionAliases descriptor,
Object owner) throws HibernateException, SQLException {
Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() );
if (element!=null) tempList.add(element);
return element;
}
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
EntityMode entityMode = getSession().getEntityMode();
ArrayList clonedList = new ArrayList( list.size() );
Iterator iter = list.iterator();
while ( iter.hasNext() ) {
Object deepCopy = persister.getElementType()
.deepCopy( iter.next(), entityMode, persister.getFactory() );
clonedList.add( deepCopy );
}
return clonedList;
}
protected Object readElementByIndex(final Object index) {
if ( !initialized ) {
class ExtraLazyElementByIndexReader implements LazyInitializationWork {
private boolean isExtraLazy;
private Object element;
@Override
public Object doWork() {
final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
final CollectionPersister persister = entry.getLoadedPersister();
isExtraLazy = persister.isExtraLazy();
if ( isExtraLazy ) {
if ( hasQueuedOperations() ) {
session.flush();
}
element = persister.getElementByIndex( entry.getLoadedKey(), index, session, owner );
}
else {
read();
}
return null;
}
}
final ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
//noinspection unchecked
withTemporarySessionIfNeeded( reader );
if ( reader.isExtraLazy ) {
return reader.element;
}
}
return UNKNOWN;
}
/**
* This version is slightly different in that here we need to assume that
* the owner is not yet associated with the session, and thus we cannot
* rely on the owner's EntityEntry snapshot...
*
* @param role The persister for the collection role being processed.
* @return
*/
final Serializable extractCollectionKeyFromOwner(CollectionPersister role) {
if ( role.getCollectionType().useLHSPrimaryKey() ) {
return ownerIdentifier;
}
else {
return ( Serializable ) role.getOwnerEntityPersister().getPropertyValue( owner, role.getCollectionType().getLHSPropertyName(), getSession().getEntityMode() );
}
}
public Serializable disassemble(CollectionPersister persister)
throws HibernateException {
Serializable[] result = new Serializable[ values.size() * 2 ];
int i=0;
for (int j=0; j< values.size(); j++) {
Object value = values.get(j);
result[i++] = persister.getIdentifierType().disassemble( identifiers.get( new Integer(j) ), getSession(), null );
result[i++] = persister.getElementType().disassemble( value, getSession(), null );
}
return result;
}
public Object replaceElements(
Object original,
Object target,
CollectionPersister persister,
Object owner,
Map copyCache,
SessionImplementor session) {
DefaultableList result = ( DefaultableList ) target;
result.clear();
result.addAll( ( DefaultableList ) original );
return result;
}
@Override
public Object processCollection(Object collection, CollectionType type) throws HibernateException {
if ( collection == CollectionType.UNFETCHED_COLLECTION ) {
return null;
}
final EventSource session = getSession();
final CollectionPersister persister = session.getFactory().getMetamodel().collectionPersister( type.getRole() );
if ( isUpdate ) {
removeCollection( persister, extractCollectionKeyFromOwner( persister ), session );
}
if ( collection != null && collection instanceof PersistentCollection ) {
final PersistentCollection wrapper = (PersistentCollection) collection;
wrapper.setCurrentSession( (SessionImplementor) session );
if ( wrapper.wasInitialized() ) {
session.getPersistenceContext().addNewCollection( persister, wrapper );
}
else {
reattachCollection( wrapper, type );
}
}
else {
// otherwise a null or brand new collection
// this will also (inefficiently) handle arrays, which
// have no snapshot, so we can't do any better
//processArrayOrNewCollection(collection, type);
}
return null;
}
@Override
public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
final Type elementType = persister.getElementType();
final List sn = (List) getSnapshot();
if ( sn.size() != bag.size() ) {
return false;
}
for ( Object elt : bag ) {
final boolean unequal = countOccurrences( elt, bag, elementType ) != countOccurrences( elt, sn, elementType );
if ( unequal ) {
return false;
}
}
return true;
}
/**
* Schedules a collection for deletion.
*
* @param role The persister representing the collection to be removed.
* @param collectionKey The collection key (differs from owner-id in the case of property-refs).
* @param source The session from which the request originated.
* @throws HibernateException
*/
void removeCollection(CollectionPersister role, Serializable collectionKey, EventSource source) throws HibernateException {
if ( log.isTraceEnabled() ) {
log.trace(
"collection dereferenced while transient " +
MessageHelper.collectionInfoString( role, ownerIdentifier, source.getFactory() )
);
}
source.getActionQueue().addAction( new CollectionRemoveAction( null, role, collectionKey, false, source ) );
}
private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
if ( log.isTraceEnabled() ) {
log.debug( "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 ) ) {
getLoadContext().getPersistenceContext().addCollectionHolder( lce.getCollection() );
}
CollectionEntry ce = getLoadContext().getPersistenceContext().getCollectionEntry( lce.getCollection() );
if ( ce == null ) {
ce = getLoadContext().getPersistenceContext().addInitializedCollection( persister, lce.getCollection(), lce.getKey() );
}
else {
ce.postInitialize( lce.getCollection() );
}
boolean addToCache = hasNoQueuedAdds && // there were no queued additions
persister.hasCache() && // and the role has a cache
session.getCacheMode().isPutEnabled() &&
!ce.isDoremove(); // and this is not a forced initialization during flush
if ( addToCache ) {
addCollectionToCache( lce, persister );
}
if ( log.isDebugEnabled() ) {
log.debug( "collection fully initialized: " + MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory() ) );
}
if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
session.getFactory().getStatisticsImplementor().loadCollection( persister.getRole() );
}
}
private void handlePotentiallyEmptyCollectionRootReturns(
LoadPlan loadPlan,
Serializable[] collectionKeys,
ResultSet resultSet,
SharedSessionContractImplementor session) {
if ( collectionKeys == null ) {
// this is not a collection initializer (and empty collections will be detected by looking for
// the owner's identifier in the result set)
return;
}
// this is a collection initializer, so we must create a collection
// for each of the passed-in keys, to account for the possibility
// that the collection is empty and has no rows in the result set
//
// todo : move this inside CollectionReturn ?
CollectionPersister persister = ( (CollectionReturn) loadPlan.getReturns().get( 0 ) ).getCollectionPersister();
for ( Serializable key : collectionKeys ) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Preparing collection intializer : %s",
MessageHelper.collectionInfoString( persister, key, session.getFactory() )
);
}
session.getPersistenceContext()
.getLoadContexts()
.getCollectionLoadContext( resultSet )
.getLoadingCollection( persister, key );
}
}