Here are the examples of the java api org.hibernate.engine.spi.SharedSessionContractImplementor.getPersistenceContext() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
53 Examples
19
Source : PessimisticForceIncrementLockingStrategy.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
if (!lockable.isVersioned()) {
throw new HibernateException("[" + lockMode + "] not supported for non-versioned enreplacedies [" + lockable.getEnreplacedyName() + "]");
}
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(object);
final EnreplacedyPersister persister = entry.getPersister();
final Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), session);
entry.forceLocked(object, nextVersion);
}
19
Source : OptimisticLockingStrategy.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
if (!lockable.isVersioned()) {
throw new OptimisticLockException(object, "[" + lockMode + "] not supported for non-versioned enreplacedies [" + lockable.getEnreplacedyName() + "]");
}
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(object);
// Register the EnreplacedyVerifyVersionProcess action to run just prior to transaction commit.
((EventSource) session).getActionQueue().registerProcess(new EnreplacedyVerifyVersionProcess(object, entry));
}
19
Source : OptimisticForceIncrementLockingStrategy.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void lock(Serializable id, Object version, Object object, int timeout, SharedSessionContractImplementor session) {
if (!lockable.isVersioned()) {
throw new HibernateException("[" + lockMode + "] not supported for non-versioned enreplacedies [" + lockable.getEnreplacedyName() + "]");
}
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(object);
// Register the EnreplacedyIncrementVersionProcess action to run just prior to transaction commit.
((EventSource) session).getActionQueue().registerProcess(new EnreplacedyIncrementVersionProcess(object, entry));
}
19
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
SharedSessionContractImplementor tempSession = null;
if (session == null) {
if (allowLoadOutsideTransaction) {
tempSession = openTemporarySessionForLoading();
} else {
throwLazyInitializationException("could not initialize proxy - no Session");
}
} else if (!session.isOpenOrWaitingForAutoClose()) {
if (allowLoadOutsideTransaction) {
tempSession = openTemporarySessionForLoading();
} else {
throwLazyInitializationException("could not initialize proxy - the owning Session was closed");
}
} else if (!session.isConnected()) {
if (allowLoadOutsideTransaction) {
tempSession = openTemporarySessionForLoading();
} else {
throwLazyInitializationException("could not initialize proxy - the owning Session is disconnected");
}
}
SharedSessionContractImplementor originalSession = null;
boolean isJTA = false;
if (tempSession != null) {
isTempSession = true;
originalSession = session;
session = tempSession;
isJTA = session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta();
if (!isJTA) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
((Session) session).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(session.getFactory().getCollectionPersister(getRole()), this);
}
try {
return lazyInitializationWork.doWork();
} finally {
if (tempSession != null) {
// make sure the just opened temp session gets closed!
isTempSession = false;
session = originalSession;
try {
if (!isJTA) {
((Session) tempSession).getTransaction().commit();
}
((Session) tempSession).close();
} catch (Exception e) {
LOG.warn("Unable to close temporary session used to load lazy collection replacedociated to no session");
}
}
}
}
19
Source : AbstractEntityInsertAction.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void afterDeserialize(SharedSessionContractImplementor session) {
super.afterDeserialize(session);
// IMPL NOTE: non-flushed changes code calls this method with session == null...
// guard against NullPointerException
if (session != null) {
final EnreplacedyEntry enreplacedyEntry = session.getPersistenceContext().getEntry(getInstance());
this.state = enreplacedyEntry.getLoadedState();
}
}
19
Source : BookstoreService.java
with Apache License 2.0
from AnghelLeonard
with Apache License 2.0
from AnghelLeonard
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = enreplacedyManager.unwrap(SharedSessionContractImplementor.clreplaced);
return sharedSession.getPersistenceContext();
}
18
Source : ComponentType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
public Object instantiate(Object parent, SharedSessionContractImplementor session) throws HibernateException {
Object result = instantiate(enreplacedyMode);
if (componentTuplizer.hasParentProperty() && parent != null) {
componentTuplizer.setParent(result, session.getPersistenceContext().proxyFor(parent), session.getFactory());
}
return result;
}
18
Source : AbstractLazyInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private Object getProxyOrNull() {
final EnreplacedyKey enreplacedyKey = generateEnreplacedyKeyOrNull(getIdentifier(), session, getEnreplacedyName());
if (enreplacedyKey != null && session != null && session.isOpen()) {
return session.getPersistenceContext().getProxy(enreplacedyKey);
}
return null;
}
18
Source : AbstractScrollableResults.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public final void close() {
if (this.closed) {
// noop if already closed
return;
}
// not absolutely necessary, but does help with aggressive release
// session.getJDBCContext().getConnectionManager().closeQueryStatement( ps, resultSet );
session.getJdbcCoordinator().getResourceRegistry().release(ps);
session.getJdbcCoordinator().afterStatementExecution();
try {
session.getPersistenceContext().getLoadContexts().cleanup(resultSet);
} catch (Throwable ignore) {
// ignore this error for now
if (LOG.isTraceEnabled()) {
LOG.tracev("Exception trying to cleanup load context : {0}", ignore.getMessage());
}
}
this.closed = true;
}
18
Source : ForeignKeys.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Is this instance persistent or detached?
* <p/>
* If <tt>replacedumed</tt> is non-null, don't hit the database to make the determination, instead replacedume that
* value; the client code must be prepared to "recover" in the case that this replacedumed result is incorrect.
*
* @param enreplacedyName The name of the enreplacedy
* @param enreplacedy The enreplacedy instance
* @param replacedumed The replacedumed return value, if avoiding database hit is desired
* @param session The session
*
* @return {@code true} if the given enreplacedy is not transient (meaning it is either detached/persistent)
*/
@SuppressWarnings("SimplifiableIfStatement")
public static boolean isNotTransient(String enreplacedyName, Object enreplacedy, Boolean replacedumed, SharedSessionContractImplementor session) {
if (enreplacedy instanceof HibernateProxy) {
return true;
}
if (session.getPersistenceContext().isEntryFor(enreplacedy)) {
return true;
}
// todo : shouldnt replacedumed be revered here?
return !isTransient(enreplacedyName, enreplacedy, replacedumed, session);
}
18
Source : AbstractEntityEntry.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public boolean isNullifiable(boolean earlyInsert, SharedSessionContractImplementor session) {
if (getStatus() == Status.SAVING) {
return true;
} else if (earlyInsert) {
return !isExistsInDatabase();
} else {
return session.getPersistenceContext().getNullifiableEnreplacedyKeys().contains(getEnreplacedyKey());
}
}
18
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Get the current snapshot from the session
*/
@SuppressWarnings({ "JavaDoc" })
protected final Serializable getSnapshot() {
return session.getPersistenceContext().getSnapshot(this);
}
17
Source : CollectionType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Get the key value from the owning enreplacedy instance, usually the identifier, but might be some
* other unique key, in the case of property-ref
*
* @param owner The collection owner
* @param session The session from which the request is originating.
* @return The collection owner's key
*/
public Serializable getKeyOfOwner(Object owner, SharedSessionContractImplementor session) {
EnreplacedyEntry enreplacedyEntry = session.getPersistenceContext().getEntry(owner);
if (enreplacedyEntry == null) {
// This just handles a particular case of component
// projection, perhaps get rid of it and throw an exception
return null;
}
if (foreignKeyPropertyName == null) {
return enreplacedyEntry.getId();
} else {
// TODO: at the point where we are resolving collection references, we don't
// know if the uk value has been resolved (depends if it was earlier or
// later in the mapping doreplacedent) - now, we could try and use e.getStatus()
// to decide to semiResolve(), trouble is that initializeEnreplacedy() reuses
// the same array for resolved and hydrated values
Object id;
if (enreplacedyEntry.getLoadedState() != null) {
id = enreplacedyEntry.getLoadedValue(foreignKeyPropertyName);
} else {
id = enreplacedyEntry.getPersister().getPropertyValue(owner, foreignKeyPropertyName);
}
// NOTE VERY HACKISH WORKAROUND!!
// TODO: Fix this so it will work for non-POJO enreplacedy mode
Type keyType = getPersister(session).getKeyType();
Clreplaced returnedClreplaced = keyType.getReturnedClreplaced();
if (!returnedClreplaced.isInstance(id)) {
id = keyType.semiResolve(enreplacedyEntry.getLoadedValue(foreignKeyPropertyName), session, owner);
}
return (Serializable) id;
}
}
17
Source : AbstractLazyInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
protected void permissiveInitialization() {
if (session == null) {
// we have a detached collection thats set to null, reattach
if (sessionFactoryUuid == null) {
throw new LazyInitializationException("could not initialize proxy [" + enreplacedyName + "#" + id + "] - no Session");
}
try {
SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setFlushMode(FlushMode.MANUAL);
boolean isJTA = session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta();
if (!isJTA) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
session.beginTransaction();
}
try {
target = session.immediateLoad(enreplacedyName, id);
initialized = true;
checkTargetState(session);
} finally {
// make sure the just opened temp session gets closed!
try {
if (!isJTA) {
session.getTransaction().commit();
}
session.close();
} catch (Exception e) {
LOG.warn("Unable to close temporary session used to load lazy proxy replacedociated to no session");
}
}
} catch (Exception e) {
LOG.error("Initialization failure [" + enreplacedyName + "#" + id + "]", e);
throw new LazyInitializationException(e.getMessage());
}
} else if (session.isOpen() && session.isConnected()) {
target = session.immediateLoad(enreplacedyName, id);
initialized = true;
checkTargetState(session);
} else {
throw new LazyInitializationException("could not initialize proxy [" + enreplacedyName + "#" + id + "] - Session was closed or disced");
}
}
17
Source : AbstractLazyInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public final void setReadOnly(boolean readOnly) {
errorIfReadOnlySettingNotAvailable();
// only update if readOnly is different from current setting
if (this.readOnly != readOnly) {
final EnreplacedyPersister persister = session.getFactory().getEnreplacedyPersister(enreplacedyName);
if (!persister.isMutable() && !readOnly) {
throw new IllegalStateException("cannot make proxies [" + enreplacedyName + "#" + id + "] for immutable enreplacedies modifiable");
}
this.readOnly = readOnly;
if (initialized) {
EnreplacedyKey key = generateEnreplacedyKeyOrNull(getIdentifier(), session, getEnreplacedyName());
if (key != null && session.getPersistenceContext().containsEnreplacedy(key)) {
session.getPersistenceContext().setReadOnly(target, readOnly);
}
}
}
}
17
Source : AbstractLazyInitializer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Attempt to initialize the proxy without loading anything from the database.
*
* This will only have any effect if the proxy is still attached to a session,
* and the enreplacedy being proxied has been loaded and added to the persistence context
* of that session since the proxy was created.
*/
public final void initializeWithoutLoadIfPossible() {
if (!initialized && session != null && session.isOpen()) {
final EnreplacedyKey key = session.generateEnreplacedyKey(getIdentifier(), session.getFactory().getMetamodel().enreplacedyPersister(getEnreplacedyName()));
final Object enreplacedy = session.getPersistenceContext().getEnreplacedy(key);
if (enreplacedy != null) {
setImplementation(enreplacedy);
}
}
}
17
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Is this the "inverse" end of a bidirectional replacedociation with
* no orphan delete enabled?
*/
@SuppressWarnings({ "JavaDoc" })
protected boolean isInverseCollectionNoOrphanDelete() {
final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null && ce.getLoadedPersister().isInverse() && !ce.getLoadedPersister().hasOrphanDelete();
}
17
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Is this the "inverse" end of a bidirectional one-to-many, or
* of a collection with no orphan delete?
*/
@SuppressWarnings({ "JavaDoc" })
protected boolean isInverseOneToManyOrNoOrphanDelete() {
final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null && ce.getLoadedPersister().isInverse() && (ce.getLoadedPersister().isOneToMany() || !ce.getLoadedPersister().hasOrphanDelete());
}
17
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Is this the "inverse" end of a bidirectional replacedociation?
*/
@SuppressWarnings({ "JavaDoc" })
protected boolean isInverseCollection() {
final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
return ce != null && ce.getLoadedPersister().isInverse();
}
17
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private SharedSessionContractImplementor openTemporarySessionForLoading() {
if (sessionFactoryUuid == null) {
throwLazyInitializationException("SessionFactory UUID not known to create temporary Session for loading");
}
final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(sessionFactoryUuid);
final SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setFlushMode(FlushMode.MANUAL);
return session;
}
17
Source : Helper.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private SharedSessionContractImplementor openTemporarySessionForLoading(LazyInitializationWork lazyInitializationWork) {
if (consumer.getSessionFactoryUuid() == null) {
throwLazyInitializationException(Cause.NO_SF_UUID, lazyInitializationWork);
}
final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory(consumer.getSessionFactoryUuid());
final SharedSessionContractImplementor session = (SharedSessionContractImplementor) sf.openSession();
session.getPersistenceContext().setDefaultReadOnly(true);
session.setHibernateFlushMode(FlushMode.MANUAL);
return session;
}
17
Source : EntityUpdateAction.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private Object[] determinePreviousNaturalIdValues(EnreplacedyPersister persister, Object[] previousState, SharedSessionContractImplementor session, Serializable id) {
if (!persister.hasNaturalIdentifier()) {
return null;
}
if (previousState != null) {
return session.getPersistenceContext().getNaturalIdHelper().extractNaturalIdValues(previousState, persister);
}
return session.getPersistenceContext().getNaturalIdSnapshot(id, persister);
}
17
Source : EntityAction.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* enreplacedy id accessor
*
* @return The enreplacedy id
*/
public final Serializable getId() {
if (id instanceof DelayedPostInsertIdentifier) {
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(instance);
if (entry == null) {
if (LOG.isDebugEnabled()) {
LOG.debugf("Skipping action - the persistence context does not contain any entry for the enreplacedy [%s]. This may occur if an enreplacedy is created and then deleted in the same transaction/flush.", instance);
}
// If an Enreplacedy is created and then deleted in the same Transaction, when Action#postDelete() calls this method the persistence context
// does not contain anymore an entry.
return null;
}
final Serializable eeId = entry.getId();
return eeId instanceof DelayedPostInsertIdentifier ? null : eeId;
}
return id;
}
16
Source : TwoPhaseLoad.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Perform the second step of 2-phase load. Fully initialize the enreplacedy
* instance.
* <p/>
* After processing a JDBC result set, we "resolve" all the replacedociations
* between the enreplacedies which were instantiated and had their state
* "hydrated" into an array
*
* @param enreplacedy The enreplacedy being loaded
* @param readOnly Is the enreplacedy being loaded as read-only
* @param session The Session
* @param preLoadEvent The (re-used) pre-load event
*/
public static void initializeEnreplacedy(final Object enreplacedy, final boolean readOnly, final SharedSessionContractImplementor session, final PreLoadEvent preLoadEvent) {
final PersistenceContext persistenceContext = session.getPersistenceContext();
final EnreplacedyEntry enreplacedyEntry = persistenceContext.getEntry(enreplacedy);
if (enreplacedyEntry == null) {
throw new replacedertionFailure("possible non-threadsafe access to the session");
}
doInitializeEnreplacedy(enreplacedy, enreplacedyEntry, readOnly, session, preLoadEvent);
}
16
Source : ForeignKeys.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Is this instance, which we know is not persistent, actually transient?
* <p/>
* If <tt>replacedumed</tt> is non-null, don't hit the database to make the determination, instead replacedume that
* value; the client code must be prepared to "recover" in the case that this replacedumed result is incorrect.
*
* @param enreplacedyName The name of the enreplacedy
* @param enreplacedy The enreplacedy instance
* @param replacedumed The replacedumed return value, if avoiding database hit is desired
* @param session The session
*
* @return {@code true} if the given enreplacedy is transient (unsaved)
*/
public static boolean isTransient(String enreplacedyName, Object enreplacedy, Boolean replacedumed, SharedSessionContractImplementor session) {
if (enreplacedy == LazyPropertyInitializer.UNFETCHED_PROPERTY) {
// an unfetched replacedociation can only point to
// an enreplacedy that already exists in the db
return false;
}
// let the interceptor inspect the instance to decide
Boolean isUnsaved = session.getInterceptor().isTransient(enreplacedy);
if (isUnsaved != null) {
return isUnsaved;
}
// let the persister inspect the instance to decide
final EnreplacedyPersister persister = session.getEnreplacedyPersister(enreplacedyName, enreplacedy);
isUnsaved = persister.isTransient(enreplacedy, session);
if (isUnsaved != null) {
return isUnsaved;
}
// we use the replacedumed value, if there is one, to avoid hitting
// the database
if (replacedumed != null) {
return replacedumed;
}
// hit the database, after checking the session cache for a snapshot
final Object[] snapshot = session.getPersistenceContext().getDatabaseSnapshot(persister.getIdentifier(enreplacedy, session), persister);
return snapshot == null;
}
16
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@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;
}
16
Source : EntityIdentityInsertAction.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void execute() throws HibernateException {
nullifyTransientReferencesIfNotAlready();
final EnreplacedyPersister persister = getPersister();
final SharedSessionContractImplementor session = getSession();
final Object instance = getInstance();
setVeto(preInsert());
// Don't need to lock the cache here, since if someone
// else inserted the same pk first, the insert would fail
if (!isVeto()) {
generatedId = persister.insert(getState(), instance, session);
if (persister.hasInsertGeneratedProperties()) {
persister.processInsertGeneratedProperties(generatedId, instance, getState(), session);
}
// need to do that here rather than in the save event listener to let
// the post insert events to have a id-filled enreplacedy when IDENreplacedY is used (EJB3)
persister.setIdentifier(instance, generatedId, session);
session.getPersistenceContext().registerInsertedKey(getPersister(), generatedId);
enreplacedyKey = session.generateEnreplacedyKey(generatedId, persister);
session.getPersistenceContext().checkUniqueness(enreplacedyKey, getInstance());
}
// TODO: this bit actually has to be called after all cascades!
// but since idenreplacedy insert is called *synchronously*,
// instead of asynchronously as other actions, it isn't
/*if ( persister.hasCache() && !persister.isCacheInvalidationRequired() ) {
cacheEntry = new CacheEntry(object, persister, session);
persister.getCache().insert(generatedId, cacheEntry);
}*/
postInsert();
if (session.getFactory().getStatistics().isStatisticsEnabled() && !isVeto()) {
session.getFactory().getStatistics().insertEnreplacedy(getPersister().getEnreplacedyName());
}
markExecuted();
}
15
Source : AbstractEntityTuplizer.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private static Serializable determineEnreplacedyId(Object enreplacedy, replacedociationType replacedociationType, SharedSessionContractImplementor session, SessionFactoryImplementor sessionFactory) {
if (enreplacedy == null) {
return null;
}
if (HibernateProxy.clreplaced.isInstance(enreplacedy)) {
// enreplacedy is a proxy, so we know it is not transient; just return ID from proxy
return ((HibernateProxy) enreplacedy).getHibernateLazyInitializer().getIdentifier();
}
if (session != null) {
final EnreplacedyEntry pcEntry = session.getPersistenceContext().getEntry(enreplacedy);
if (pcEntry != null) {
// enreplacedy managed; return ID.
return pcEntry.getId();
}
}
final EnreplacedyPersister persister = resolveEnreplacedyPersister(enreplacedy, replacedociationType, session, sessionFactory);
return persister.getIdentifier(enreplacedy, session);
}
15
Source : ResultSetProcessingContextImpl.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private void registerNonExists(EnreplacedyFetch fetch) {
final EnreplacedyType fetchedType = fetch.getFetchedType();
if (!fetchedType.isOneToOne()) {
return;
}
final EnreplacedyReferenceProcessingState fetchOwnerState = getOwnerProcessingState(fetch);
if (fetchOwnerState == null) {
throw new IllegalStateException("Could not locate fetch owner state");
}
final EnreplacedyKey ownerEnreplacedyKey = fetchOwnerState.getEnreplacedyKey();
if (ownerEnreplacedyKey == null) {
throw new IllegalStateException("Could not locate fetch owner EnreplacedyKey");
}
session.getPersistenceContext().addNullProperty(ownerEnreplacedyKey, fetchedType.getPropertyName());
}
15
Source : ResultSetProcessingContextImpl.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private void createSubselects() {
if (subselectLoadableEnreplacedyKeyMap == null || nRowsRead <= 1) {
LOG.tracef("Skipping create subselects because there are fewer than 2 results, so query by key is more efficient.", getClreplaced().getName());
// early return
return;
}
final Map<String, int[]> namedParameterLocMap = ResultSetProcessorHelper.buildNamedParameterLocMap(queryParameters, namedParameterContext);
final String subselectQueryString = SubselectFetch.createSubselectFetchQueryFragment(queryParameters);
for (Map.Entry<EnreplacedyReference, Set<EnreplacedyKey>> entry : subselectLoadableEnreplacedyKeyMap.entrySet()) {
if (!entry.getKey().getEnreplacedyPersister().hreplacedubselectLoadableCollections()) {
continue;
}
SubselectFetch subselectFetch = new SubselectFetch(subselectQueryString, aliasResolutionContext.resolveSqlTableAliasFromQuerySpaceUid(entry.getKey().getQuerySpaceUid()), (Loadable) entry.getKey().getEnreplacedyPersister(), queryParameters, entry.getValue(), namedParameterLocMap);
for (EnreplacedyKey key : entry.getValue()) {
session.getPersistenceContext().getBatchFetchQueue().addSubselect(key, subselectFetch);
}
}
}
15
Source : TwoPhaseLoad.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Add an uninitialized instance of an enreplacedy clreplaced, as a placeholder to ensure object
* idenreplacedy. Must be called before <tt>postHydrate()</tt>.
*
* Create a "temporary" entry for a newly instantiated enreplacedy. The enreplacedy is uninitialized,
* but we need the mapping from id to instance in order to guarantee uniqueness.
*
* @param key The enreplacedy key
* @param object The enreplacedy instance
* @param persister The enreplacedy persister
* @param lockMode The lock mode
* @param session The Session
*/
public static void addUninitializedEnreplacedy(final EnreplacedyKey key, final Object object, final EnreplacedyPersister persister, final LockMode lockMode, final SharedSessionContractImplementor session) {
session.getPersistenceContext().addEnreplacedy(object, Status.LOADING, null, key, null, lockMode, true, persister, false);
}
15
Source : TwoPhaseLoad.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Same as {@link #addUninitializedEnreplacedy}, but here for an enreplacedy from the second level cache
*
* @param key The enreplacedy key
* @param object The enreplacedy instance
* @param persister The enreplacedy persister
* @param lockMode The lock mode
* @param version The version
* @param session The Session
*/
public static void addUninitializedCachedEnreplacedy(final EnreplacedyKey key, final Object object, final EnreplacedyPersister persister, final LockMode lockMode, final Object version, final SharedSessionContractImplementor session) {
session.getPersistenceContext().addEnreplacedy(object, Status.LOADING, null, key, version, lockMode, true, persister, false);
}
14
Source : OneToOneType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public boolean isNull(Object owner, SharedSessionContractImplementor session) {
if (propertyName != null) {
final EnreplacedyPersister ownerPersister = session.getFactory().getMetamodel().enreplacedyPersister(enreplacedyName);
final Serializable id = session.getContextEnreplacedyIdentifier(owner);
final EnreplacedyKey enreplacedyKey = session.generateEnreplacedyKey(id, ownerPersister);
return session.getPersistenceContext().isPropertyNull(enreplacedyKey, getPropertyName());
} else {
return false;
}
}
14
Source : TwoPhaseLoad.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Register the "hydrated" state of an enreplacedy instance, after the first step of 2-phase loading.
*
* Add the "hydrated state" (an array) of an uninitialized enreplacedy to the session. We don't try
* to resolve any replacedociations yet, because there might be other enreplacedies waiting to be
* read from the JDBC result set we are currently processing
*
* @param persister The persister for the hydrated enreplacedy
* @param id The enreplacedy identifier
* @param values The enreplacedy values
* @param rowId The rowId for the enreplacedy
* @param object An optional instance for the enreplacedy being loaded
* @param lockMode The lock mode
* @param session The Session
*/
public static void postHydrate(final EnreplacedyPersister persister, final Serializable id, final Object[] values, final Object rowId, final Object object, final LockMode lockMode, final SharedSessionContractImplementor session) {
final Object version = Versioning.getVersion(values, persister);
session.getPersistenceContext().addEntry(object, Status.LOADING, values, rowId, id, version, lockMode, true, persister, false);
if (version != null && LOG.isTraceEnabled()) {
final String versionStr = persister.isVersioned() ? persister.getVersionType().toLoggableString(version, session.getFactory()) : "null";
LOG.tracef("Version: %s", versionStr);
}
}
14
Source : BatchFetchQueueHelper.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Remove the enreplacedy key with the specified {@code id} and {@code persister} from
* the batch loadable enreplacedies {@link BatchFetchQueue}.
*
* @param id - the ID for the enreplacedy to be removed
* @param persister - the enreplacedy persister
* @param session - the session
*/
public static void removeBatchLoadableEnreplacedyKey(Serializable id, EnreplacedyPersister persister, SharedSessionContractImplementor session) {
final EnreplacedyKey enreplacedyKey = session.generateEnreplacedyKey(id, persister);
final BatchFetchQueue batchFetchQueue = session.getPersistenceContext().getBatchFetchQueue();
batchFetchQueue.removeBatchLoadableEnreplacedyKey(enreplacedyKey);
}
13
Source : EntityType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Load an instance by a unique key that is not the primary key.
*
* @param enreplacedyName The name of the enreplacedy to load
* @param uniqueKeyPropertyName The name of the property defining the uniqie key.
* @param key The unique key property value.
* @param session The originating session.
*
* @return The loaded enreplacedy
*
* @throws HibernateException generally indicates problems performing the load.
*/
public Object loadByUniqueKey(String enreplacedyName, String uniqueKeyPropertyName, Object key, SharedSessionContractImplementor session) throws HibernateException {
final SessionFactoryImplementor factory = session.getFactory();
UniqueKeyLoadable persister = (UniqueKeyLoadable) factory.getMetamodel().enreplacedyPersister(enreplacedyName);
// TODO: implement 2nd level caching?! natural id caching ?! proxies?!
EnreplacedyUniqueKey euk = new EnreplacedyUniqueKey(enreplacedyName, uniqueKeyPropertyName, key, getIdentifierOrUniqueKeyType(factory), persister.getEnreplacedyMode(), session.getFactory());
final PersistenceContext persistenceContext = session.getPersistenceContext();
Object result = persistenceContext.getEnreplacedy(euk);
if (result == null) {
result = persister.loadByUniqueKey(uniqueKeyPropertyName, key, session);
// If the enreplacedy was not in the Persistence Context, but was found now,
// add it to the Persistence Context
if (result != null) {
persistenceContext.addEnreplacedy(euk, result);
}
}
return result == null ? null : persistenceContext.proxyFor(result);
}
13
Source : CollectionType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private void preserveSnapshot(PersistentCollection original, PersistentCollection result, Type elemType, Object owner, Map copyCache, SharedSessionContractImplementor session) {
Serializable originalSnapshot = original.getStoredSnapshot();
Serializable resultSnapshot = result.getStoredSnapshot();
Serializable targetSnapshot;
if (originalSnapshot instanceof List) {
targetSnapshot = new ArrayList(((List) originalSnapshot).size());
for (Object obj : (List) originalSnapshot) {
((List) targetSnapshot).add(elemType.replace(obj, null, session, owner, copyCache));
}
} else if (originalSnapshot instanceof Map) {
if (originalSnapshot instanceof SortedMap) {
targetSnapshot = new TreeMap(((SortedMap) originalSnapshot).comparator());
} else {
targetSnapshot = new HashMap(CollectionHelper.determineProperSizing(((Map) originalSnapshot).size()), CollectionHelper.LOAD_FACTOR);
}
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) originalSnapshot).entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
Object resultSnapshotValue = (resultSnapshot == null) ? null : ((Map<Object, Object>) resultSnapshot).get(key);
Object newValue = elemType.replace(value, resultSnapshotValue, session, owner, copyCache);
if (key == value) {
((Map) targetSnapshot).put(newValue, newValue);
} else {
((Map) targetSnapshot).put(key, newValue);
}
}
} else if (originalSnapshot instanceof Object[]) {
Object[] arr = (Object[]) originalSnapshot;
for (int i = 0; i < arr.length; i++) {
arr[i] = elemType.replace(arr[i], null, session, owner, copyCache);
}
targetSnapshot = originalSnapshot;
} else {
// retain the same snapshot
targetSnapshot = resultSnapshot;
}
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(result);
if (ce != null) {
ce.resetStoredSnapshot(result, targetSnapshot);
}
}
13
Source : ResultSetProcessorImpl.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
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 preplaceded-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);
}
}
13
Source : EntityReferenceInitializerImpl.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private void checkVersion(SharedSessionContractImplementor session, ResultSet resultSet, EnreplacedyPersister persister, EnreplacedyAliases enreplacedyAliases, EnreplacedyKey enreplacedyKey, Object enreplacedyInstance) {
final Object version = session.getPersistenceContext().getEntry(enreplacedyInstance).getVersion();
if (version != null) {
// null version means the object is in the process of being loaded somewhere else in the ResultSet
VersionType versionType = persister.getVersionType();
final Object currentVersion;
try {
currentVersion = versionType.nullSafeGet(resultSet, enreplacedyAliases.getSuffixedVersionAliases(), session, null);
} catch (SQLException e) {
throw session.getFactory().getServiceRegistry().getService(JdbcServices.clreplaced).getSqlExceptionHelper().convert(e, "Could not read version value from result set");
}
if (!versionType.isEqual(version, currentVersion)) {
if (session.getFactory().getStatistics().isStatisticsEnabled()) {
session.getFactory().getStatistics().optimisticFailure(persister.getEnreplacedyName());
}
throw new StaleObjectStateException(persister.getEnreplacedyName(), enreplacedyKey.getIdentifier());
}
}
}
13
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
private String generateUnexpectedSessionStateMessage(SharedSessionContractImplementor session) {
// NOTE: If this.session != null, this.session may be operating on this collection
// (e.g., by changing this.role, this.key, or even this.session) in a different thread.
// Grab the current role and key (it can still get changed by this.session...)
// If this collection is connected to this.session, then this.role and this.key should
// be consistent with the CollectionEntry in this.session (as long as this.session doesn't
// change it). Don't access the CollectionEntry in this.session because that could result
// in multi-threaded access to this.session.
final String roleCurrent = role;
final Serializable keyCurrent = key;
final StringBuilder sb = new StringBuilder("Collection : ");
if (roleCurrent != null) {
sb.append(MessageHelper.collectionInfoString(roleCurrent, keyCurrent));
} else {
final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(this);
if (ce != null) {
sb.append(MessageHelper.collectionInfoString(ce.getLoadedPersister(), this, ce.getLoadedKey(), session));
} else {
sb.append("<unknown>");
}
}
// only include the collection contents if debug logging
if (LOG.isDebugEnabled()) {
final String collectionContents = wasInitialized() ? toString() : "<uninitialized>";
sb.append("\nCollection contents: [").append(collectionContents).append("]");
}
return sb.toString();
}
12
Source : NamedQueryLoader.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public Object load(Serializable id, Object optionalObject, SharedSessionContractImplementor session) {
LOG.debugf("Loading enreplacedy: %s using named query: %s", persister.getEnreplacedyName(), queryName);
// IMPL NOTE: essentially we perform the named query (which loads the enreplacedy into the PC), and then
// do an internal lookup of the enreplacedy from the PC.
final AbstractProducedQuery query = (AbstractProducedQuery) session.getNamedQuery(queryName);
if (query.getParameterMetadata().hasNamedParameters()) {
query.setParameter(query.getNamedParameters()[0], id, persister.getIdentifierType());
} else {
query.setParameter(position, id, persister.getIdentifierType());
}
query.setOptionalId(id);
query.setOptionalEnreplacedyName(persister.getEnreplacedyName());
query.setOptionalObject(optionalObject);
query.setFlushMode(FlushMode.MANUAL);
query.list();
// now look up the object we are really interested in!
// (this lets us correctly handle proxies and multi-row or multi-column queries)
return session.getPersistenceContext().getEnreplacedy(session.generateEnreplacedyKey(id, persister));
}
12
Source : AbstractPersistentCollection.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Given a collection of enreplacedy 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 enreplacedyName, 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 EnreplacedyPersister enreplacedyPersister = session.getFactory().getEnreplacedyPersister(enreplacedyName);
final Type idType = enreplacedyPersister.getIdentifierType();
final boolean useIdDirect = mayUseIdDirect(idType);
// create the collection holding the Orphans
final Collection res = new ArrayList();
// collect EnreplacedyIdentifier(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 IdenreplacedySet();
for (Object current : currentElements) {
if (current != null && ForeignKeys.isNotTransient(enreplacedyName, current, null, session)) {
final EnreplacedyEntry ee = session.getPersistenceContext().getEntry(current);
if (ee != null && ee.getStatus() == Status.SAVING) {
currentSaving.add(current);
} else {
final Serializable currentId = ForeignKeys.getEnreplacedyIdentifierIfNotUnsaved(enreplacedyName, 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.getEnreplacedyIdentifierIfNotUnsaved(enreplacedyName, old, session);
if (!currentIds.contains(useIdDirect ? oldId : new TypedValue(idType, oldId))) {
res.add(old);
}
}
}
return res;
}
10
Source : TwoPhaseLoad.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* PostLoad cannot occur during initializeEnreplacedy, as that call occurs *before*
* the Set collections are added to the persistence context by Loader.
* Without the split, LazyInitializationExceptions can occur in the Enreplacedy's
* postLoad if it acts upon the collection.
*
* HHH-6043
*
* @param enreplacedy The enreplacedy
* @param session The Session
* @param postLoadEvent The (re-used) post-load event
*/
public static void postLoad(final Object enreplacedy, final SharedSessionContractImplementor session, final PostLoadEvent postLoadEvent) {
if (session.isEventSource()) {
final PersistenceContext persistenceContext = session.getPersistenceContext();
final EnreplacedyEntry enreplacedyEntry = persistenceContext.getEntry(enreplacedy);
postLoadEvent.setEnreplacedy(enreplacedy).setId(enreplacedyEntry.getId()).setPersister(enreplacedyEntry.getPersister());
final EventListenerGroup<PostLoadEventListener> listenerGroup = session.getFactory().getServiceRegistry().getService(EventListenerRegistry.clreplaced).getEventListenerGroup(EventType.POST_LOAD);
for (PostLoadEventListener listener : listenerGroup.listeners()) {
listener.onPostLoad(postLoadEvent);
}
}
}
8
Source : CollectionLoadContext.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* Finish the process of collection-loading for this bound result set. Mainly this
* involves cleaning up resources and notifying the collections that loading is
* complete.
*
* @param persister The persister for which to complete loading.
*/
public void endLoadingCollections(CollectionPersister persister) {
final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
if (!loadContexts.hasLoadingCollectionEntries() && localLoadingCollectionKeys.isEmpty()) {
return;
}
// in an effort to avoid concurrent-modification-exceptions (from
// potential recursive calls back through here as a result of the
// eventual call to PersistentCollection#endRead), we scan the
// internal loadingCollections map for matches and store those matches
// in a temp collection. the temp collection is then used to "drive"
// the #endRead processing.
List<LoadingCollectionEntry> matches = null;
final Iterator itr = localLoadingCollectionKeys.iterator();
while (itr.hasNext()) {
final CollectionKey collectionKey = (CollectionKey) itr.next();
final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry(collectionKey);
if (lce == null) {
LOG.loadingCollectionKeyNotFound(collectionKey);
} else if (lce.getResultSet() == resultSet && lce.getPersister() == persister) {
if (matches == null) {
matches = new ArrayList<>();
}
matches.add(lce);
if (lce.getCollection().getOwner() == null) {
session.getPersistenceContext().addUnownedCollection(new CollectionKey(persister, lce.getKey(), persister.getOwnerEnreplacedyPersister().getEnreplacedyMetamodel().getEnreplacedyMode()), lce.getCollection());
}
LOG.tracev("Removing collection load entry [{0}]", lce);
// todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)...
loadContexts.unregisterLoadingCollectionXRef(collectionKey);
itr.remove();
}
}
endLoadingCollections(persister, matches);
if (localLoadingCollectionKeys.isEmpty()) {
// todo : hack!!!
// NOTE : here we cleanup the load context when we have no more local
// LCE entries. This "works" for the time being because really
// only the collection load contexts are implemented. Long term,
// this cleanup should become part of the "close result set"
// processing from the (sandbox/jdbc) jdbc-container code.
loadContexts.cleanup(resultSet);
}
}
7
Source : DynamicBatchingEntityLoaderBuilder.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@SuppressWarnings("unchecked")
private List performOrderedMultiLoad(OuterJoinLoadable persister, Serializable[] ids, SharedSessionContractImplementor session, MultiLoadOptions loadOptions) {
replacedert loadOptions.isOrderReturnEnabled();
final List result = CollectionHelper.arrayList(ids.length);
final LockOptions lockOptions = (loadOptions.getLockOptions() == null) ? new LockOptions(LockMode.NONE) : loadOptions.getLockOptions();
final int maxBatchSize;
if (loadOptions.getBatchSize() != null && loadOptions.getBatchSize() > 0) {
maxBatchSize = loadOptions.getBatchSize();
} else {
maxBatchSize = session.getJdbcServices().getJdbcEnvironment().getDialect().getDefaultBatchLoadSizingStrategy().determineOptimalBatchLoadSize(persister.getIdentifierType().getColumnSpan(session.getFactory()), ids.length);
}
final List<Serializable> idsInBatch = new ArrayList<>();
final List<Integer> elementPositionsLoadedByBatch = new ArrayList<>();
for (int i = 0; i < ids.length; i++) {
final Serializable id = ids[i];
final EnreplacedyKey enreplacedyKey = new EnreplacedyKey(id, persister);
if (loadOptions.isSessionCheckingEnabled()) {
// look for it in the Session first
final Object managedEnreplacedy = session.getPersistenceContext().getEnreplacedy(enreplacedyKey);
if (managedEnreplacedy != null) {
if (!loadOptions.isReturnOfDeletedEnreplacediesEnabled()) {
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(managedEnreplacedy);
if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
// put a null in the result
result.add(i, null);
continue;
}
}
// if we did not hit the continue above, there is already an
// entry in the PC for that enreplacedy, so use it...
result.add(i, managedEnreplacedy);
continue;
}
}
// if we did not hit any of the continues above, then we need to batch
// load the enreplacedy state.
idsInBatch.add(ids[i]);
if (idsInBatch.size() >= maxBatchSize) {
performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
}
// Save the EnreplacedyKey instance for use later!
result.add(i, enreplacedyKey);
elementPositionsLoadedByBatch.add(i);
}
if (!idsInBatch.isEmpty()) {
performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
}
for (Integer position : elementPositionsLoadedByBatch) {
// the element value at this position in the result List should be
// the EnreplacedyKey for that enreplacedy; reuse it!
final EnreplacedyKey enreplacedyKey = (EnreplacedyKey) result.get(position);
Object enreplacedy = session.getPersistenceContext().getEnreplacedy(enreplacedyKey);
if (enreplacedy != null && !loadOptions.isReturnOfDeletedEnreplacediesEnabled()) {
// make sure it is not DELETED
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(enreplacedy);
if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
// the enreplacedy is locally deleted, and the options ask that we not return such enreplacedies...
enreplacedy = null;
}
}
result.set(position, enreplacedy);
}
return result;
}
6
Source : AbstractLoadPlanBasedLoader.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
protected List executeLoad(SharedSessionContractImplementor session, QueryParameters queryParameters, LoadQueryDetails loadQueryDetails, boolean returnProxies, ResultTransformer forcedResultTransformer, List<AfterLoadAction> afterLoadActions) throws SQLException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
final boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
if (queryParameters.isReadOnlyInitialized()) {
// The read-only/modifiable mode for the query was explicitly set.
// Temporarily set the default read-only/modifiable setting to the query's setting.
persistenceContext.setDefaultReadOnly(queryParameters.isReadOnly());
} else {
// The read-only/modifiable setting for the query was not initialized.
// Use the default read-only/modifiable from the persistence context instead.
queryParameters.setReadOnly(persistenceContext.isDefaultReadOnly());
}
persistenceContext.beforeLoad();
try {
List results = null;
final String sql = loadQueryDetails.getSqlStatement();
SqlStatementWrapper wrapper = null;
try {
wrapper = executeQueryStatement(sql, queryParameters, false, afterLoadActions, session);
results = loadQueryDetails.getResultSetProcessor().extractResults(wrapper.getResultSet(), session, queryParameters, new NamedParameterContext() {
@Override
public int[] getNamedParameterLocations(String name) {
return AbstractLoadPlanBasedLoader.this.getNamedParameterLocs(name);
}
}, returnProxies, queryParameters.isReadOnly(), forcedResultTransformer, afterLoadActions);
} finally {
if (wrapper != null) {
session.getJdbcCoordinator().getResourceRegistry().release(wrapper.getResultSet(), wrapper.getStatement());
session.getJdbcCoordinator().getResourceRegistry().release(wrapper.getStatement());
session.getJdbcCoordinator().afterStatementExecution();
}
persistenceContext.afterLoad();
}
persistenceContext.initializeNonLazyCollections();
return results;
} finally {
// Restore the original default
persistenceContext.setDefaultReadOnly(defaultReadOnlyOrig);
}
}
6
Source : DynamicBatchingEntityLoaderBuilder.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@SuppressWarnings("unchecked")
protected List performUnorderedMultiLoad(OuterJoinLoadable persister, Serializable[] ids, SharedSessionContractImplementor session, MultiLoadOptions loadOptions) {
replacedert !loadOptions.isOrderReturnEnabled();
final List result = CollectionHelper.arrayList(ids.length);
if (loadOptions.isSessionCheckingEnabled()) {
// the user requested that we exclude ids corresponding to already managed
// enreplacedies from the generated load SQL. So here we will iterate all
// incoming id values and see whether it corresponds to an existing
// enreplacedy replacedociated with the PC - if it does we add it to the result
// list immediately and remove its id from the group of ids to load.
boolean foundAnyManagedEnreplacedies = false;
final List<Serializable> nonManagedIds = new ArrayList<Serializable>();
for (Serializable id : ids) {
final EnreplacedyKey enreplacedyKey = new EnreplacedyKey(id, persister);
final Object managedEnreplacedy = session.getPersistenceContext().getEnreplacedy(enreplacedyKey);
if (managedEnreplacedy != null) {
if (!loadOptions.isReturnOfDeletedEnreplacediesEnabled()) {
final EnreplacedyEntry entry = session.getPersistenceContext().getEntry(managedEnreplacedy);
if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
continue;
}
}
foundAnyManagedEnreplacedies = true;
result.add(managedEnreplacedy);
} else {
nonManagedIds.add(id);
}
}
if (foundAnyManagedEnreplacedies) {
if (nonManagedIds.isEmpty()) {
// all of the given ids were already replacedociated with the Session
return result;
} else {
// over-write the ids to be loaded with the collection of
// just non-managed ones
ids = nonManagedIds.toArray((Serializable[]) Array.newInstance(ids.getClreplaced().getComponentType(), nonManagedIds.size()));
}
}
}
final LockOptions lockOptions = (loadOptions.getLockOptions() == null) ? new LockOptions(LockMode.NONE) : loadOptions.getLockOptions();
int numberOfIdsLeft = ids.length;
final int maxBatchSize;
if (loadOptions.getBatchSize() != null && loadOptions.getBatchSize() > 0) {
maxBatchSize = loadOptions.getBatchSize();
} else {
maxBatchSize = session.getJdbcServices().getJdbcEnvironment().getDialect().getDefaultBatchLoadSizingStrategy().determineOptimalBatchLoadSize(persister.getIdentifierType().getColumnSpan(session.getFactory()), numberOfIdsLeft);
}
int idPosition = 0;
while (numberOfIdsLeft > 0) {
int batchSize = Math.min(numberOfIdsLeft, maxBatchSize);
final DynamicEnreplacedyLoader batchingLoader = new DynamicEnreplacedyLoader(persister, batchSize, lockOptions, session.getFactory(), session.getLoadQueryInfluencers());
Serializable[] idsInBatch = new Serializable[batchSize];
System.arraycopy(ids, idPosition, idsInBatch, 0, batchSize);
QueryParameters qp = buildMultiLoadQueryParameters(persister, idsInBatch, lockOptions);
result.addAll(batchingLoader.doEnreplacedyBatchFetch(session, qp, idsInBatch));
numberOfIdsLeft = numberOfIdsLeft - batchSize;
idPosition += batchSize;
}
return result;
}
6
Source : EntityDeleteAction.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public void execute() throws HibernateException {
final Serializable id = getId();
final EnreplacedyPersister persister = getPersister();
final SharedSessionContractImplementor session = getSession();
final Object instance = getInstance();
final boolean veto = preDelete();
Object version = this.version;
if (persister.isVersionPropertyGenerated()) {
// we need to grab the version value from the enreplacedy, otherwise
// we have issues with generated-version enreplacedies that may have
// multiple actions queued during the same flush
version = persister.getVersion(instance);
}
final Object ck;
if (persister.canWriteToCache()) {
final EnreplacedyDataAccess cache = persister.getCacheAccessStrategy();
ck = cache.generateCacheKey(id, persister, session.getFactory(), session.getTenantIdentifier());
lock = cache.lockItem(session, ck, version);
} else {
ck = null;
}
if (!isCascadeDeleteEnabled && !veto) {
persister.delete(id, version, instance, session);
}
// postDelete:
// After actually deleting a row, record the fact that the instance no longer
// exists on the database (needed for idenreplacedy-column key generation), and
// remove it from the session cache
final PersistenceContext persistenceContext = session.getPersistenceContext();
final EnreplacedyEntry entry = persistenceContext.removeEntry(instance);
if (entry == null) {
throw new replacedertionFailure("possible nonthreadsafe access to session");
}
entry.postDelete();
persistenceContext.removeEnreplacedy(entry.getEnreplacedyKey());
persistenceContext.removeProxy(entry.getEnreplacedyKey());
if (persister.canWriteToCache()) {
persister.getCacheAccessStrategy().remove(session, ck);
}
persistenceContext.getNaturalIdHelper().removeSharedNaturalIdCrossReference(persister, id, naturalIdValues);
postDelete();
if (getSession().getFactory().getStatistics().isStatisticsEnabled() && !veto) {
getSession().getFactory().getStatistics().deleteEnreplacedy(getPersister().getEnreplacedyName());
}
}
5
Source : ResultSetProcessorImpl.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
@Override
public List extractResults(ResultSet resultSet, final SharedSessionContractImplementor session, QueryParameters queryParameters, NamedParameterContext namedParameterContext, boolean returnProxies, boolean readOnly, ResultTransformer forcedResultTransformer, List<AfterLoadAction> afterLoadActionList) throws SQLException {
handlePotentiallyEmptyCollectionRootReturns(loadPlan, queryParameters.getCollectionKeys(), resultSet, session);
final int maxRows;
final RowSelection selection = queryParameters.getRowSelection();
if (LimitHelper.hasMaxRows(selection)) {
maxRows = selection.getMaxRows();
LOG.tracef("Limiting ResultSet processing to just %s rows", maxRows);
} else {
maxRows = Integer.MAX_VALUE;
}
// Handles the "FETCH ALL PROPERTIES" directive in HQL
final boolean forceFetchLazyAttributes = false;
final ResultSetProcessingContextImpl context = new ResultSetProcessingContextImpl(resultSet, session, loadPlan, aliasResolutionContext, readOnly, shouldUseOptionalEnreplacedyInstance, forceFetchLazyAttributes, returnProxies, queryParameters, namedParameterContext, hadSubselectFetches);
final List loadResults = new ArrayList();
LOG.trace("Processing result set");
int count;
for (count = 0; count < maxRows && resultSet.next(); count++) {
LOG.debugf("Starting ResultSet row #%s", count);
Object logicalRow = rowReader.readRow(resultSet, context);
// todo : apply transformers here?
loadResults.add(logicalRow);
context.finishUpRow();
}
LOG.tracev("Done processing result set ({0} rows)", count);
rowReader.finishUp(context, afterLoadActionList);
context.wrapUp();
session.getPersistenceContext().initializeNonLazyCollections();
return loadResults;
}
4
Source : CollectionType.java
with GNU General Public License v2.0
from lamsfoundation
with GNU General Public License v2.0
from lamsfoundation
/**
* instantiate a collection wrapper (called when loading an object)
*
* @param key The collection owner key
* @param session The session from which the request is originating.
* @param owner The collection owner
* @return The collection
*/
public Object getCollection(Serializable key, SharedSessionContractImplementor session, Object owner, Boolean overridingEager) {
CollectionPersister persister = getPersister(session);
final PersistenceContext persistenceContext = session.getPersistenceContext();
final EnreplacedyMode enreplacedyMode = persister.getOwnerEnreplacedyPersister().getEnreplacedyMode();
// check if collection is currently being loaded
PersistentCollection collection = persistenceContext.getLoadContexts().locateLoadingCollection(persister, key);
if (collection == null) {
// check if it is already completely loaded, but unowned
collection = persistenceContext.useUnownedCollection(new CollectionKey(persister, key, enreplacedyMode));
if (collection == null) {
collection = persistenceContext.getCollection(new CollectionKey(persister, key, enreplacedyMode));
if (collection == null) {
// create a new collection wrapper, to be initialized later
collection = instantiate(session, persister, key);
collection.setOwner(owner);
persistenceContext.addUninitializedCollection(persister, collection, key);
// some collections are not lazy:
boolean eager = overridingEager != null ? overridingEager : !persister.isLazy();
if (initializeImmediately()) {
session.initializeCollection(collection, false);
} else if (eager) {
persistenceContext.addNonLazyCollection(collection);
}
if (hasHolder()) {
session.getPersistenceContext().addCollectionHolder(collection);
}
}
}
if (LOG.isTraceEnabled()) {
LOG.tracef("Created collection wrapper: %s", MessageHelper.collectionInfoString(persister, collection, key, session));
}
}
collection.setOwner(owner);
return collection.getValue();
}
See More Examples