use of org.hibernate.internal.util.collections.IdentitySet in project hibernate-orm by hibernate.
the class AbstractPersistentCollection method getOrphans.
/**
* Given a collection of entity instances that used to
* 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, SharedSessionContractImplementor session) throws HibernateException {
// short-circuit(s)
if (currentElements.size() == 0) {
// no new elements, the old list contains only Orphans
return oldElements;
}
if (oldElements.size() == 0) {
// no old elements, so no Orphans neither
return oldElements;
}
final EntityPersister entityPersister = session.getFactory().getEntityPersister(entityName);
final Type idType = entityPersister.getIdentifierType();
final boolean useIdDirect = mayUseIdDirect(idType);
// create the collection holding the Orphans
final Collection res = new ArrayList();
// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
final java.util.Set currentIds = new HashSet();
final java.util.Set currentSaving = new IdentitySet();
for (Object current : currentElements) {
if (current != null && ForeignKeys.isNotTransient(entityName, current, null, session)) {
final EntityEntry ee = session.getPersistenceContext().getEntry(current);
if (ee != null && ee.getStatus() == Status.SAVING) {
currentSaving.add(current);
} else {
final Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, current, session);
currentIds.add(useIdDirect ? currentId : new TypedValue(idType, currentId));
}
}
}
// iterate over the *old* list
for (Object old : oldElements) {
if (!currentSaving.contains(old)) {
final Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, old, session);
if (!currentIds.contains(useIdDirect ? oldId : new TypedValue(idType, oldId))) {
res.add(old);
}
}
}
return res;
}
Aggregations