Search in sources :

Example 86 with UnitOfWorkImpl

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

the class Runner1 method run.

@Override
public void run() {
    try {
        EntityManager em = emf.createEntityManager();
        Department dept = em.find(Department.class, deptPK);
        Equipment equip = em.find(Equipment.class, equipPK);
        dept.getEquipment().put(equip.getId(), equip);
        UnitOfWorkImpl uow = ((EntityManagerImpl) em).getActivePersistenceContext(null);
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
        }
        uow.issueSQLbeforeCompletion(true);
        synchronized (this.waitOn) {
            try {
                this.waitOn.notify();
                this.waitOn.wait();
            } catch (InterruptedException e) {
            }
        }
        CacheKey cacheKey = uow.getParent().getParent().getIdentityMapAccessorInstance().getCacheKeyForObject(dept);
        synchronized (cacheKey) {
            cacheKey.notify();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
        }
        uow.mergeClonesAfterCompletion();
    } catch (Exception ex) {
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) Equipment(org.eclipse.persistence.testing.models.jpa.advanced.Equipment) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) CacheKey(org.eclipse.persistence.internal.identitymaps.CacheKey)

Example 87 with UnitOfWorkImpl

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

the class AbstractTransactionController method getActiveUnitOfWork.

/**
 * INTERNAL:
 * Return the active unit of work for the current external transaction.
 * If no transaction is active then return null. If a transaction is active
 * but no unit of work has been bound to it then create and return one.
 */
@Override
public UnitOfWorkImpl getActiveUnitOfWork() {
    Object transaction = getTransaction();
    if (transaction == null) {
        return null;
    }
    UnitOfWorkImpl activeUnitOfWork = lookupActiveUnitOfWork(transaction);
    if (activeUnitOfWork == null) {
        // Txn is active but no UoW has been associated with it yet, so create one.
        activeUnitOfWork = getSession().acquireUnitOfWork();
        Object transactionKey = getTransactionKey(transaction);
        addUnitOfWork(transactionKey, activeUnitOfWork);
        activeUnitOfWork.setTransaction(transaction);
        this.activeUnitOfWorkThreadLocal.set(activeUnitOfWork);
    }
    return activeUnitOfWork;
}
Also used : UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)

Example 88 with UnitOfWorkImpl

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

the class EntityManagerImpl method refresh.

/**
 * Refresh the state of the instance from the database, overwriting changes
 * made to the entity, if any, and lock it with respect to given lock mode
 * type. If the lock mode type is pessimistic and the entity instance is
 * found but cannot be locked: - the PessimisticLockException will be thrown
 * if the database locking failure causes transaction-level rollback. - the
 * LockTimeoutException will be thrown if the database locking failure
 * causes only statement-level rollback If a vendor-specific property or
 * hint is not recognized, it is silently ignored. Portable applications
 * should not rely on the standard timeout hint. Depending on the database
 * in use and the locking mechanisms used by the provider, the hint may or
 * may not be observed.
 *
 * @param properties
 *            standard and vendor-specific properties and hints
 * @throws IllegalArgumentException
 *             if the instance is not an entity or the entity is not managed
 * @throws TransactionRequiredException
 *             if there is no transaction
 * @throws EntityNotFoundException
 *             if the entity no longer exists in the database
 * @throws PessimisticLockException
 *             if pessimistic locking fails and the transaction is rolled
 *             back
 * @throws LockTimeoutException
 *             if pessimistic locking fails and only the statement is rolled
 *             back
 * @throws PersistenceException
 *             if an unsupported lock call is made
 */
@Override
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    try {
        verifyOpen();
        boolean validateExistence = (lockMode != null && !lockMode.equals(LockModeType.NONE));
        UnitOfWorkImpl uow = getActivePersistenceContext(checkForTransaction(validateExistence));
        if (!contains(entity, uow)) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_refresh_not_managed_object", new Object[] { entity }));
        }
        // Get the read object query and apply the properties to it.
        ReadObjectQuery query = getReadObjectQuery(entity, properties);
        // the properties.
        if (properties == null || !properties.containsKey(QueryHints.REFRESH)) {
            query.refreshIdentityMapResult();
        }
        if (properties == null || !properties.containsKey(QueryHints.REFRESH_CASCADE)) {
            query.cascadeByMapping();
        }
        Object refreshedEntity = executeQuery(query, lockMode, uow);
        if (refreshedEntity == null) {
            // invalidated if refresh returns null.
            throw new EntityNotFoundException(ExceptionLocalization.buildMessage("entity_no_longer_exists_in_db", new Object[] { entity }));
        }
    } catch (LockTimeoutException e) {
        throw e;
    } catch (RuntimeException exception) {
        setRollbackOnly();
        throw exception;
    }
}
Also used : ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) LockTimeoutException(jakarta.persistence.LockTimeoutException)

Example 89 with UnitOfWorkImpl

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

the class EntityManagerImpl method lock.

/**
 * Set the lock mode for an entity object contained in the persistence
 * context.
 *
 * @throws PersistenceException
 *             if an unsupported lock call is made
 * @throws IllegalArgumentException
 *             if the instance is not an entity or is a detached entity
 * @throws jakarta.persistence.TransactionRequiredException
 *             if there is no transaction
 */
@Override
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    try {
        verifyOpen();
        if (entity == null) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] { null }));
        }
        // Throws TransactionRequiredException if no active transaction.
        UnitOfWorkImpl uow = getActivePersistenceContext(checkForTransaction(true));
        if (!contains(entity, uow)) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_lock_not_managed_object", new Object[] { entity }));
        }
        if (lockMode == null || lockMode.name().equals(ObjectLevelReadQuery.NONE)) {
            // Nothing to do
            return;
        }
        // Must avoid using the new JPA 2.0 Enum values directly to allow JPA 1.0 jars to still work.
        if (lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_READ) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_WRITE) || lockMode.name().equals(ObjectLevelReadQuery.PESSIMISTIC_FORCE_INCREMENT)) {
            // return if the entity has previously been pessimistically locked
            if (uow.isPessimisticLocked(entity)) {
                return;
            }
            // Get the read object query and apply the properties to it.
            ReadObjectQuery query = getReadObjectQuery(entity, properties);
            // the properties.
            if (properties == null || !properties.containsKey(QueryHints.REFRESH)) {
                query.refreshIdentityMapResult();
            }
            if (properties == null || !properties.containsKey(QueryHints.REFRESH_CASCADE)) {
                query.cascadePrivateParts();
            }
            executeQuery(query, lockMode, getActivePersistenceContext(checkForTransaction(false)));
        } else {
            RepeatableWriteUnitOfWork context = getActivePersistenceContext(checkForTransaction(false));
            ClassDescriptor descriptor = context.getDescriptor(entity);
            OptimisticLockingPolicy lockingPolicy = descriptor.getOptimisticLockingPolicy();
            if ((lockingPolicy == null) || !(lockingPolicy instanceof VersionLockingPolicy)) {
                throw new PersistenceException(ExceptionLocalization.buildMessage("ejb30-wrong-lock_called_without_version_locking-index", null));
            }
            context.forceUpdateToVersionField(entity, (lockMode == LockModeType.WRITE || lockMode.name().equals(ObjectLevelReadQuery.OPTIMISTIC_FORCE_INCREMENT)));
        }
    } catch (LockTimeoutException e) {
        throw e;
    } catch (RuntimeException e) {
        setRollbackOnly();
        throw e;
    }
}
Also used : ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) VersionLockingPolicy(org.eclipse.persistence.descriptors.VersionLockingPolicy) PersistenceException(jakarta.persistence.PersistenceException) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) LockTimeoutException(jakarta.persistence.LockTimeoutException) OptimisticLockingPolicy(org.eclipse.persistence.internal.descriptors.OptimisticLockingPolicy)

Example 90 with UnitOfWorkImpl

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

the class EntityManagerImpl method unwrap.

/**
 * Return an object of the specified type to allow access to the
 * provider-specific API. If the provider's EntityManager implementation
 * does not support the specified class, the PersistenceException is thrown.
 *
 * @param cls
 *            the class of the object to be returned. This is normally
 *            either the underlying EntityManager implementation class or an
 *            interface that it implements.
 * @return an instance of the specified class
 * @throws PersistenceException
 *             if the provider does not support the call.
 *
 * @since Java Persistence API 2.0
 */
@Override
public <T> T unwrap(Class<T> cls) {
    try {
        if (cls.equals(UnitOfWork.class) || cls.equals(UnitOfWorkImpl.class) || cls.equals(RepeatableWriteUnitOfWork.class)) {
            return (T) this.getUnitOfWork();
        } else if (cls.equals(JpaEntityManager.class) || cls.equals(EntityManagerImpl.class)) {
            return (T) this;
        } else if (cls.equals(Session.class) || cls.equals(AbstractSession.class)) {
            return (T) this.getAbstractSession();
        } else if (cls.equals(DatabaseSession.class) || cls.equals(DatabaseSessionImpl.class)) {
            return (T) this.getDatabaseSession();
        } else if (cls.equals(Server.class) || cls.equals(ServerSession.class)) {
            return (T) this.getServerSession();
        } else if (cls.equals(SessionBroker.class)) {
            return (T) this.getSessionBroker();
        } else if (cls.equals(java.sql.Connection.class)) {
            final UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl) this.getUnitOfWork();
            Accessor accessor = unitOfWork.getAccessor();
            if (unitOfWork.getParent().isExclusiveIsolatedClientSession()) {
                // If the ExclusiveIsolatedClientSession hasn't serviced a query prior to the unwrap,
                // there will be no available Connection.
                java.sql.Connection conn = accessor.getConnection();
                if (conn == null) {
                    final boolean uowInTran = unitOfWork.isInTransaction();
                    final boolean activeTran = checkForTransaction(false) != null;
                    if (uowInTran || activeTran) {
                        if (activeTran) {
                            unitOfWork.beginEarlyTransaction();
                        }
                        accessor.incrementCallCount(unitOfWork.getParent());
                        accessor.decrementCallCount();
                        conn = accessor.getConnection();
                    }
                // if not in a tx, still return null
                }
                return (T) conn;
            } else if (unitOfWork.isInTransaction()) {
                return (T) unitOfWork.getAccessor().getConnection();
            }
            if (checkForTransaction(false) != null) {
                unitOfWork.beginEarlyTransaction();
                accessor = unitOfWork.getAccessor();
                // Ensure external connection is acquired.
                accessor.incrementCallCount(unitOfWork.getParent());
                accessor.decrementCallCount();
                return (T) accessor.getConnection();
            }
            return null;
        } else if (cls.getName().equals("jakarta.resource.cci.Connection")) {
            UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl) this.getUnitOfWork();
            if (unitOfWork.isInTransaction() || unitOfWork.getParent().isExclusiveIsolatedClientSession()) {
                return (T) unitOfWork.getAccessor().getConnection();
            }
            if (checkForTransaction(false) != null) {
                unitOfWork.beginEarlyTransaction();
                Accessor accessor = unitOfWork.getAccessor();
                // Ensure external connection is acquired.
                accessor.incrementCallCount(unitOfWork.getParent());
                accessor.decrementCallCount();
                return (T) accessor.getDatasourceConnection();
            }
            return null;
        }
        throw new PersistenceException(ExceptionLocalization.buildMessage("unable_to_unwrap_jpa", new String[] { EntityManager.class.getName(), cls.getName() }));
    } catch (RuntimeException e) {
        throw e;
    }
}
Also used : ServerSession(org.eclipse.persistence.sessions.server.ServerSession) Server(org.eclipse.persistence.sessions.server.Server) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) Accessor(org.eclipse.persistence.internal.databaseaccess.Accessor) PersistenceException(jakarta.persistence.PersistenceException) RepeatableWriteUnitOfWork(org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) DatabaseSession(org.eclipse.persistence.sessions.DatabaseSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Session(org.eclipse.persistence.sessions.Session) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

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