Search in sources :

Example 71 with UnitOfWorkImpl

use of org.eclipse.persistence.internal.sessions.UnitOfWorkImpl in project eclipselink by eclipse-ee4j.

the class ReadAllQuery method execute.

/**
 * INTERNAL:
 * Execute the query. If there are cached results return those.
 * This must override the super to support result caching.
 *
 * @param session - the session in which the receiver will be executed.
 * @return An object or vector, the result of executing the query.
 * @exception DatabaseException - an error has occurred on the database
 */
@Override
public Object execute(AbstractSession session, AbstractRecord row) throws DatabaseException {
    if (shouldCacheQueryResults()) {
        if (getContainerPolicy().overridesRead()) {
            throw QueryException.cannotCacheCursorResultsOnQuery(this);
        }
        if (shouldConformResultsInUnitOfWork()) {
            throw QueryException.cannotConformAndCacheQueryResults(this);
        }
        if (isPrepared()) {
            // only prepared queries can have cached results.
            Object queryResults = getQueryResults(session, row, true);
            if (queryResults != null) {
                if (QueryMonitor.shouldMonitor()) {
                    QueryMonitor.incrementReadAllHits(this);
                }
                session.incrementProfile(SessionProfiler.CacheHits, this);
                // results, and return an empty container instance as configured
                if (queryResults == InvalidObject.instance) {
                    return getContainerPolicy().containerInstance(0);
                }
                Collection results = (Collection) queryResults;
                if (session.isUnitOfWork()) {
                    ContainerPolicy policy = getContainerPolicy();
                    Object resultCollection = policy.containerInstance(results.size());
                    Object iterator = policy.iteratorFor(results);
                    while (policy.hasNext(iterator)) {
                        Object result = ((UnitOfWorkImpl) session).registerExistingObject(policy.next(iterator, session), this.descriptor, null, true);
                        policy.addInto(result, resultCollection, session);
                    }
                    return resultCollection;
                }
                return results;
            }
        }
        session.incrementProfile(SessionProfiler.CacheMisses, this);
    }
    if (QueryMonitor.shouldMonitor()) {
        QueryMonitor.incrementReadAllMisses(this);
    }
    return super.execute(session, row);
}
Also used : ContainerPolicy(org.eclipse.persistence.internal.queries.ContainerPolicy) Collection(java.util.Collection) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) InvalidObject(org.eclipse.persistence.internal.helper.InvalidObject)

Example 72 with UnitOfWorkImpl

use of org.eclipse.persistence.internal.sessions.UnitOfWorkImpl in project eclipselink by eclipse-ee4j.

the class ReadObjectQuery method checkEarlyReturnLocal.

/**
 * INTERNAL:
 * The cache check is done before the prepare as a hit will not require the work to be done.
 */
@Override
protected Object checkEarlyReturnLocal(AbstractSession session, AbstractRecord translationRow) {
    if (shouldCheckCache() && shouldMaintainCache() && (!shouldRefreshIdentityMapResult() && (!shouldRetrieveBypassCache())) && (!(session.isRemoteSession() && (shouldRefreshRemoteIdentityMapResult() || this.descriptor.shouldDisableCacheHitsOnRemote()))) && (!(shouldCheckDescriptorForCacheUsage() && this.descriptor.shouldDisableCacheHits())) && (!this.descriptor.isDescriptorForInterface())) {
        Object cachedObject = getQueryMechanism().checkCacheForObject(translationRow, session);
        this.isCacheCheckComplete = true;
        // key expression or selection object/key just abort.
        if (cachedObject == InvalidObject.instance) {
            return cachedObject;
        }
        if (cachedObject != null) {
            if (shouldLoadResultIntoSelectionObject()) {
                ObjectBuilder builder = this.descriptor.getObjectBuilder();
                builder.copyInto(cachedObject, getSelectionObject());
                // put this object into the cache.  This may cause some loss of identity
                session.getIdentityMapAccessorInstance().putInIdentityMap(getSelectionObject());
                cachedObject = getSelectionObject();
            }
            // check locking.  If clone has not been locked, do not early return cached object
            if (isLockQuery() && (session.isUnitOfWork() && !((UnitOfWorkImpl) session).isPessimisticLocked(cachedObject))) {
                return null;
            }
            if (QueryMonitor.shouldMonitor()) {
                QueryMonitor.incrementReadObjectHits(this);
            }
            session.incrementProfile(SessionProfiler.CacheHits, this);
        } else {
            if (!session.isUnitOfWork()) {
                if (QueryMonitor.shouldMonitor()) {
                    QueryMonitor.incrementReadObjectMisses(this);
                }
                session.incrementProfile(SessionProfiler.CacheMisses, this);
            }
        }
        if (shouldUseWrapperPolicy()) {
            cachedObject = this.descriptor.getObjectBuilder().wrapObject(cachedObject, session);
        }
        return cachedObject;
    } else {
        if (!session.isUnitOfWork()) {
            if (QueryMonitor.shouldMonitor()) {
                QueryMonitor.incrementReadObjectMisses(this);
            }
            session.incrementProfile(SessionProfiler.CacheMisses, this);
        }
        return null;
    }
}
Also used : UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) InvalidObject(org.eclipse.persistence.internal.helper.InvalidObject) ObjectBuilder(org.eclipse.persistence.internal.descriptors.ObjectBuilder)

Example 73 with UnitOfWorkImpl

use of org.eclipse.persistence.internal.sessions.UnitOfWorkImpl in project eclipselink by eclipse-ee4j.

the class ReadObjectQuery method executeObjectLevelReadQuery.

/**
 * INTERNAL:
 * Execute the query.
 * Do a cache lookup and build object from row if required.
 * @exception  DatabaseException - an error has occurred on the database
 * @return object - the first object found or null if none.
 */
@Override
protected Object executeObjectLevelReadQuery() throws DatabaseException {
    if (this.descriptor.isDescriptorForInterface() || this.descriptor.hasTablePerClassPolicy()) {
        Object returnValue = this.descriptor.getInterfacePolicy().selectOneObjectUsingMultipleTableSubclassRead(this);
        if (this.descriptor.hasTablePerClassPolicy() && (!this.descriptor.isAbstract()) && (returnValue == null)) {
        // let it fall through to query the root.
        } else {
            this.executionTime = System.currentTimeMillis();
            return returnValue;
        }
    }
    boolean shouldSetRowsForJoins = hasJoining() && this.joinedAttributeManager.isToManyJoin();
    AbstractSession session = getSession();
    Object result = null;
    AbstractRecord row = null;
    Object sopObject = getTranslationRow().getSopObject();
    boolean useOptimization = false;
    if (sopObject == null) {
        useOptimization = usesResultSetAccessOptimization();
    }
    if (useOptimization) {
        DatabaseCall call = ((DatasourceCallQueryMechanism) this.queryMechanism).selectResultSet();
        this.executionTime = System.currentTimeMillis();
        boolean exceptionOccured = false;
        ResultSet resultSet = call.getResult();
        DatabaseAccessor dbAccessor = (DatabaseAccessor) getAccessor();
        try {
            if (resultSet.next()) {
                ResultSetMetaData metaData = call.getResult().getMetaData();
                boolean useSimple = this.descriptor.getObjectBuilder().isSimple();
                DatabasePlatform platform = dbAccessor.getPlatform();
                boolean optimizeData = platform.shouldOptimizeDataConversion();
                if (useSimple) {
                    row = new SimpleResultSetRecord(call.getFields(), call.getFieldsArray(), resultSet, metaData, dbAccessor, getExecutionSession(), platform, optimizeData);
                    if (this.descriptor.isDescriptorTypeAggregate()) {
                        // Aggregate Collection may have an unmapped primary key referencing the owner, the corresponding field will not be used when the object is populated and therefore may not be cleared.
                        ((SimpleResultSetRecord) row).setShouldKeepValues(true);
                    }
                } else {
                    row = new ResultSetRecord(call.getFields(), call.getFieldsArray(), resultSet, metaData, dbAccessor, getExecutionSession(), platform, optimizeData);
                }
                if (session.isUnitOfWork()) {
                    result = registerResultInUnitOfWork(row, (UnitOfWorkImpl) session, this.translationRow, true);
                } else {
                    result = buildObject(row);
                }
                if (!useSimple && this.descriptor.getObjectBuilder().shouldKeepRow()) {
                    if (((ResultSetRecord) row).hasResultSet()) {
                        // ResultSet has not been fully triggered - that means the cached object was used.
                        // Yet the row still may be cached in a value holder (see loadBatchReadAttributes and loadJoinedAttributes methods).
                        // Remove ResultSet to avoid attempt to trigger it (already closed) when pk or fk values (already extracted) accessed when the value holder is instantiated.
                        ((ResultSetRecord) row).removeResultSet();
                    } else {
                        ((ResultSetRecord) row).removeNonIndirectionValues();
                    }
                }
            }
        } catch (SQLException exception) {
            exceptionOccured = true;
            DatabaseException commException = dbAccessor.processExceptionForCommError(session, exception, call);
            if (commException != null) {
                throw commException;
            }
            throw DatabaseException.sqlException(exception, call, getAccessor(), session, false);
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (dbAccessor != null) {
                    if (call.getStatement() != null) {
                        dbAccessor.releaseStatement(call.getStatement(), call.getSQLString(), call, session);
                    }
                }
                if (call.hasAllocatedConnection()) {
                    getExecutionSession().releaseConnectionAfterCall(this);
                }
            } catch (RuntimeException cleanupException) {
                if (!exceptionOccured) {
                    throw cleanupException;
                }
            } catch (SQLException cleanupSQLException) {
                if (!exceptionOccured) {
                    throw DatabaseException.sqlException(cleanupSQLException, call, dbAccessor, session, false);
                }
            }
        }
    } else {
        if (sopObject != null) {
            row = new DatabaseRecord(0);
            row.setSopObject(sopObject);
        } else {
            // If using 1-m joins, must select all rows.
            if (shouldSetRowsForJoins) {
                List rows = getQueryMechanism().selectAllRows();
                if (rows.size() > 0) {
                    row = (AbstractRecord) rows.get(0);
                }
                getJoinedAttributeManager().setDataResults(rows, session);
            } else {
                row = getQueryMechanism().selectOneRow();
            }
        }
        this.executionTime = System.currentTimeMillis();
        if (row != null) {
            if (session.isUnitOfWork()) {
                result = registerResultInUnitOfWork(row, (UnitOfWorkImpl) session, this.translationRow, true);
            } else {
                result = buildObject(row);
            }
            if (sopObject != null) {
                // remove sopObject so it's not stuck in a value holder.
                row.setSopObject(null);
            }
        }
    }
    if ((result == null) && shouldCacheQueryResults()) {
        cacheResult(null);
    }
    if ((result == null) && this.shouldRefreshIdentityMapResult) {
        // bug5955326, should invalidate the shared cached if refreshed object no longer exists.
        if (this.selectionId != null) {
            session.getParentIdentityMapSession(this.descriptor, true, true).getIdentityMapAccessor().invalidateObject(this.selectionId, this.referenceClass);
        } else if (this.selectionObject != null) {
            session.getParentIdentityMapSession(this.descriptor, true, true).getIdentityMapAccessor().invalidateObject(this.selectionObject);
        }
    }
    if (this.shouldIncludeData && (sopObject == null)) {
        ComplexQueryResult complexResult = new ComplexQueryResult();
        complexResult.setResult(result);
        complexResult.setData(row);
        return complexResult;
    }
    return result;
}
Also used : DatabaseRecord(org.eclipse.persistence.sessions.DatabaseRecord) SQLException(java.sql.SQLException) DatasourceCallQueryMechanism(org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) SimpleResultSetRecord(org.eclipse.persistence.internal.sessions.SimpleResultSetRecord) ResultSetRecord(org.eclipse.persistence.internal.sessions.ResultSetRecord) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) SimpleResultSetRecord(org.eclipse.persistence.internal.sessions.SimpleResultSetRecord) DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) InvalidObject(org.eclipse.persistence.internal.helper.InvalidObject) DatabaseAccessor(org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor) List(java.util.List) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 74 with UnitOfWorkImpl

use of org.eclipse.persistence.internal.sessions.UnitOfWorkImpl in project eclipselink by eclipse-ee4j.

the class ResultSetMappingQuery method executeDatabaseQuery.

/**
 * INTERNAL:
 * Executes the prepared query on the datastore.
 */
@Override
public Object executeDatabaseQuery() throws DatabaseException {
    if (getSession().isUnitOfWork()) {
        UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl) getSession();
        // transaction early on the parent also.
        if (isLockQuery()) {
            if ((!unitOfWork.getCommitManager().isActive()) && (!unitOfWork.wasTransactionBegunPrematurely())) {
                unitOfWork.beginTransaction();
                unitOfWork.setWasTransactionBegunPrematurely(true);
            }
        }
        if (unitOfWork.isNestedUnitOfWork()) {
            // execute in parent UOW then register normally here.
            UnitOfWorkImpl nestedUnitOfWork = (UnitOfWorkImpl) getSession();
            setSession(nestedUnitOfWork.getParent());
            Object result = executeDatabaseQuery();
            setSession(nestedUnitOfWork);
            Object clone = registerIndividualResult(result, null, unitOfWork, null, null);
            if (shouldUseWrapperPolicy()) {
                clone = getDescriptor().getObjectBuilder().wrapObject(clone, unitOfWork);
            }
            return clone;
        }
    }
    // this will update the query with any settings
    session.validateQuery(this);
    if (getQueryId() == 0) {
        setQueryId(getSession().getNextQueryId());
    }
    if (getCall().isExecuteUpdate()) {
        DatabaseCall call = ((StoredProcedureCall) getQueryMechanism().execute());
        setExecutionTime(System.currentTimeMillis());
        return call;
    } else {
        Vector rows = getQueryMechanism().executeSelect();
        setExecutionTime(System.currentTimeMillis());
        // If using 1-m joins, must set all rows.
        return buildObjectsFromRecords(rows);
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) Vector(java.util.Vector)

Example 75 with UnitOfWorkImpl

use of org.eclipse.persistence.internal.sessions.UnitOfWorkImpl in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testDetachChildObjects.

public void testDetachChildObjects() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    InitTestDetachChildObjects(em);
    UnitOfWorkImpl uow = (UnitOfWorkImpl) em.unwrap(JpaEntityManager.class).getActiveSession();
    Material mat = em.find(Material.class, 1L);
    mat.setWert("WERT3");
    MaterialEreignis matEreignis1 = new MaterialEreignis();
    matEreignis1.setChangedObject(mat);
    matEreignis1.setBeforeChange(mat.getLastHist());
    MaterialHist afterMat1 = makeHistCopy(mat);
    matEreignis1.setAfterChange(afterMat1);
    em.persist(matEreignis1);
    em.flush();
    em.detach(matEreignis1);
    List<PlanArbeitsgangHist> pagList = getInstancesFromPC(PlanArbeitsgangHist.class, uow);
    assertTrue(pagList.isEmpty());
    for (PlanArbeitsgangHist pag : pagList) {
        assertTrue(em.contains(pag));
    }
    rollbackTransaction(em);
    closeEntityManager(em);
}
Also used : MaterialEreignis(org.eclipse.persistence.testing.models.jpa.advanced.MaterialEreignis) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) MaterialHist(org.eclipse.persistence.testing.models.jpa.advanced.MaterialHist) PlanArbeitsgangHist(org.eclipse.persistence.testing.models.jpa.advanced.PlanArbeitsgangHist) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) Material(org.eclipse.persistence.testing.models.jpa.advanced.Material)

Aggregations

UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)92 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)21 TestErrorException (org.eclipse.persistence.testing.framework.TestErrorException)19 Employee (org.eclipse.persistence.testing.models.employee.domain.Employee)18 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)15 EntityManager (jakarta.persistence.EntityManager)14 InvalidObject (org.eclipse.persistence.internal.helper.InvalidObject)11 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)9 Vector (java.util.Vector)8 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)8 Department (org.eclipse.persistence.testing.models.jpa.advanced.Department)8 CacheKey (org.eclipse.persistence.internal.identitymaps.CacheKey)7 EntityManagerImpl (org.eclipse.persistence.internal.jpa.EntityManagerImpl)7 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)7 DatabaseException (org.eclipse.persistence.exceptions.DatabaseException)6 UnitOfWorkChangeSet (org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet)6 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)5 BigDecimal (java.math.BigDecimal)5 ExpressionBuilder (org.eclipse.persistence.expressions.ExpressionBuilder)5 ReadAllQuery (org.eclipse.persistence.queries.ReadAllQuery)5