Search in sources :

Example 6 with LockModeType

use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.

the class JPAQuery method processJPQLQuery.

/**
 * INTERNAL:
 * Convert the JPA query into a DatabaseQuery.
 */
public DatabaseQuery processJPQLQuery(Session session) {
    ClassLoader classloader = session.getDatasourcePlatform().getConversionManager().getLoader();
    LockModeType lockModeEnum = null;
    // Must handle errors if a JPA 2.0 option is used in JPA 1.0.
    try {
        lockModeEnum = LockModeType.valueOf(lockMode);
    } catch (Exception ignore) {
    // Ignore JPA 2.0 in JPA 1.0, reverts to no lock.
    }
    DatabaseQuery ejbquery = EJBQueryImpl.buildEJBQLDatabaseQuery(getName(), jpqlString, (AbstractSession) session, lockModeEnum, hints, classloader);
    ejbquery.setName(getName());
    return ejbquery;
}
Also used : DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) LockModeType(jakarta.persistence.LockModeType) OptimisticLockException(org.eclipse.persistence.exceptions.OptimisticLockException) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException)

Example 7 with LockModeType

use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method getLockMode.

/**
 * @see jakarta.persistence.EntityManager#getLockMode(java.lang.Object)
 * @since Java Persistence API 2.0
 */
@Override
public LockModeType getLockMode(Object entity) {
    try {
        verifyOpen();
        checkForTransaction(true);
        UnitOfWorkImpl uowImpl = getActivePersistenceContext(checkForTransaction(false));
        LockModeType lockMode = LockModeType.NONE;
        if (!contains(entity, uowImpl)) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_getLockMode_of_not_managed_object", new Object[] { entity }));
        }
        Boolean optimistickLock = (Boolean) uowImpl.getOptimisticReadLockObjects().get(entity);
        if (optimistickLock != null) {
            if (optimistickLock.equals(Boolean.FALSE)) {
                lockMode = LockModeType.OPTIMISTIC;
            } else {
                // PESSIMISTIC_FORCE_INCREMENT
                if (uowImpl.getPessimisticLockedObjects().get(entity) != null) {
                    lockMode = LockModeType.PESSIMISTIC_FORCE_INCREMENT;
                } else {
                    lockMode = LockModeType.OPTIMISTIC_FORCE_INCREMENT;
                }
            }
        } else {
            // Not optimistically locked
            if (uowImpl.getPessimisticLockedObjects().get(entity) != null) {
                lockMode = LockModeType.PESSIMISTIC_WRITE;
            }
        }
        return lockMode;
    } catch (RuntimeException exception) {
        setRollbackOnly();
        throw exception;
    }
}
Also used : UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) LockModeType(jakarta.persistence.LockModeType)

Example 8 with LockModeType

use of jakarta.persistence.LockModeType in project hibernate-orm by hibernate.

the class QueryHintDefinition method determineLockOptions.

public LockOptions determineLockOptions(NamedQuery namedQueryAnnotation) {
    final LockModeType lockModeType = namedQueryAnnotation.lockMode();
    final Integer lockTimeoutHint = specLockTimeout();
    final Boolean followOnLocking = getBooleanWrapper(HibernateHints.HINT_FOLLOW_ON_LOCKING);
    return determineLockOptions(lockModeType, lockTimeoutHint, followOnLocking);
}
Also used : LockModeType(jakarta.persistence.LockModeType)

Example 9 with LockModeType

use of jakarta.persistence.LockModeType in project hibernate-orm by hibernate.

the class NamedQueryHelper method determineLockOptions.

private static LockOptions determineLockOptions(Map<String, Object> hints, SessionFactoryImplementor sessionFactory) {
    final Object lockModeSetting = hints.get(HINT_NATIVE_LOCK_MODE);
    final LockMode lockMode;
    if (lockModeSetting == null) {
        lockMode = LockMode.NONE;
    } else if (lockModeSetting instanceof LockMode) {
        lockMode = (LockMode) lockModeSetting;
    } else if (lockModeSetting instanceof LockModeType) {
        lockMode = LockModeTypeHelper.getLockMode((LockModeType) lockModeSetting);
    } else {
        lockMode = LockMode.fromExternalForm(lockModeSetting.toString());
    }
    if (lockMode == LockMode.NONE) {
        return LockOptions.NONE;
    } else {
        return new LockOptions(lockMode);
    }
}
Also used : LockOptions(org.hibernate.LockOptions) LockModeType(jakarta.persistence.LockModeType) LockMode(org.hibernate.LockMode)

Example 10 with LockModeType

use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testPESSIMISTIC_ExtendedScope.

public void testPESSIMISTIC_ExtendedScope() {
    // Cannot create parallel entity managers in the server. Uses FOR UPDATE clause which SQLServer doesn't support.
    if (isOnServer() || !isSelectForUpateSupported() || !isPessimisticWriteLockSupported()) {
        return;
    }
    // If FOR UPDATE NOWAIT is not supported then FOR UPDATE is used - and that could lock the test (em2) for a long time (depending on db setting).
    boolean shouldSpawnThread = !isSelectForUpateNoWaitSupported();
    // To avoid that a separate thread is spawned that - after waiting the specified time -
    // completes the locking transaction (em1) and therefore clears the way to em2 go ahead.
    long timeToWait = 1000;
    String errorMsg = "";
    LockModeType lockMode = LockModeType.PESSIMISTIC_WRITE;
    // create Employee with Projects and Responsibilities
    Employee emp = new Employee();
    emp.setFirstName("PESSIMISTIC");
    emp.setLastName("ExtendedScope");
    emp.addResponsibility("0");
    emp.addResponsibility("1");
    SmallProject smallProject = new SmallProject();
    smallProject.setName("SmallExtendedScope");
    emp.addProject(smallProject);
    LargeProject largeProject = new LargeProject();
    largeProject.setName("LargeExtendedScope");
    largeProject.setBudget(5000);
    emp.addProject(largeProject);
    // persist
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        em.persist(emp);
        commitTransaction(em);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
    // cache ids
    int id = emp.getId();
    int smallProjId = smallProject.getId();
    clearCache();
    // properties to be passed to find, lock, refresh methods
    Map<String, Object> properties = new HashMap();
    properties.put(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
    DatabasePlatform platform = (DatabasePlatform) getPlatform();
    String forUpdateClause = platform.getSelectForUpdateString();
    if (isSelectForUpateNoWaitSupported()) {
        properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
        forUpdateClause = platform.getSelectForUpdateNoWaitString();
    }
    String lockingClauseAfterWhereClause = "";
    String lockingClauseBeforeWhereClause = "";
    if (platform.shouldPrintLockingClauseAfterWhereClause()) {
        lockingClauseAfterWhereClause = forUpdateClause;
    } else {
        lockingClauseBeforeWhereClause = forUpdateClause;
    }
    SessionBroker broker = getSessionBroker();
    // indicates whether the object to be locked is already in cache.
    boolean[] isObjectCached = { false, true };
    // indicates which method on the first entity manager is used to lock the object.
    String[] testModeArray1 = { "query", "find", "lock", "refresh" };
    // indicates which method on the second entity manager is used to test the lock.
    String[] testModeArray2 = { "query", "find", "update_name", "update_salary", "remove_project", "remove_respons", "update_project", "update_respons", "lock", "refresh" };
    // testMode1 loop
    for (int i = 0; i < testModeArray1.length; i++) {
        String testMode1 = testModeArray1[i];
        // isObjectCached loop
        for (int k = 0; k < isObjectCached.length; k++) {
            boolean isObjCached = isObjectCached[k];
            // testMode2 loop
            for (int j = 0; j < testModeArray2.length; j++) {
                String testMode2 = testModeArray2[j];
                boolean isExceptionExpected = !testMode2.equals("update_project");
                // lock emp using em1
                EntityManager em1 = createEntityManager();
                // bring object into cache if required
                if (isObjCached) {
                    broker.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: bring object into cache", null, null, false);
                    em1.find(Employee.class, id);
                }
                Employee emp1;
                try {
                    beginTransaction(em1);
                    broker.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode1 = " + testMode1, null, null, false);
                    if (testMode1.equals("query")) {
                        Query query1 = em1.createQuery("SELECT emp FROM Employee emp WHERE emp.id = " + id).setLockMode(lockMode).setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
                        if (isSelectForUpateNoWaitSupported()) {
                            query1.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
                        }
                        emp1 = (Employee) query1.getSingleResult();
                    } else if (testMode1.equals("find")) {
                        emp1 = em1.find(Employee.class, id, lockMode, properties);
                    } else {
                        emp1 = em1.find(Employee.class, id);
                        if (testMode1.equals("lock")) {
                            em1.lock(emp1, lockMode, properties);
                        } else if (testMode1.equals("refresh")) {
                            em1.refresh(emp1, lockMode, properties);
                        } else {
                            fail("Unknown testMode1 = " + testMode1);
                        }
                    }
                    TransactionKiller transactionKiller = null;
                    // try to update emp using em2
                    EntityManager em2 = createEntityManager();
                    Employee emp2;
                    try {
                        beginTransaction(em2);
                        broker.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode2 = " + testMode2, null, null, false);
                        if (shouldSpawnThread) {
                            // after waiting TransactionKiller rollback em1 transaction unlocking way for em2 to proceed.
                            // the test assumes that em2 waiting for timeToWait means em2 waiting on the lock acquired by em1.
                            transactionKiller = new TransactionKiller(em1, timeToWait);
                            transactionKiller.start();
                        }
                        if (testMode2.equals("query")) {
                            Query query2 = em2.createQuery("SELECT emp FROM Employee emp WHERE emp.id = " + id).setLockMode(lockMode).setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
                            if (isSelectForUpateNoWaitSupported()) {
                                query2.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
                            }
                            emp2 = (Employee) query2.getSingleResult();
                        } else if (testMode2.equals("find")) {
                            emp2 = em2.find(Employee.class, id, lockMode, properties);
                        } else if (testMode2.equals("update_name")) {
                            em2.createNativeQuery("SELECT L_NAME FROM MBR2_EMPLOYEE" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(2)).getSingleResult();
                        // em2.createNativeQuery("UPDATE CMP3_EMPLOYEE SET L_NAME = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
                        } else if (testMode2.equals("update_salary")) {
                            em2.createNativeQuery("SELECT SALARY FROM MBR2_SALARY" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(2)).getSingleResult();
                        // em2.createNativeQuery("UPDATE CMP3_SALARY SET SALARY = 1000 WHERE EMP_ID = "+id).executeUpdate();
                        } else if (testMode2.equals("remove_project")) {
                            em2.createNativeQuery("SELECT PROJECTS_PROJ_ID FROM MBR3_EMP_PROJ" + lockingClauseBeforeWhereClause + " WHERE EMPLOYEES_EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(3)).getResultList();
                        // em2.createNativeQuery("DELETE FROM CMP3_EMP_PROJ WHERE EMPLOYEES_EMP_ID = "+id).executeUpdate();
                        } else if (testMode2.equals("remove_respons")) {
                            em2.createNativeQuery("SELECT EMP_ID FROM MBR1_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(1)).getResultList();
                        // em2.createNativeQuery("DELETE FROM CMP3_RESPONS WHERE EMP_ID = "+id).executeUpdate();
                        } else if (testMode2.equals("update_project")) {
                            em2.createNativeQuery("SELECT PROJ_NAME FROM MBR3_PROJECT" + lockingClauseBeforeWhereClause + " WHERE PROJ_ID = " + smallProjId + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(3)).getSingleResult();
                        // em2.createNativeQuery("UPDATE CMP3_PROJECT SET PROJ_NAME = 'NEW' WHERE PROJ_ID = "+smallProjId).executeUpdate();
                        } else if (testMode2.equals("update_respons")) {
                            em2.createNativeQuery("SELECT DESCRIPTION FROM MBR1_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(1)).getResultList();
                        // em2.createNativeQuery("UPDATE CMP3_RESPONS SET DESCRIPTION = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
                        } else {
                            emp2 = em2.find(Employee.class, id);
                            if (testMode2.equals("lock")) {
                                em2.lock(emp2, lockMode, properties);
                            } else if (testMode2.equals("refresh")) {
                                em2.refresh(emp2, lockMode, properties);
                            } else {
                                fail("Unknown testMode2 = " + testMode2);
                            }
                        }
                        // commitTransaction(em2);
                        boolean hasKilledTransaction = false;
                        if (transactionKiller != null) {
                            transactionKiller.shouldKillTransaction = false;
                            try {
                                transactionKiller.join();
                            } catch (InterruptedException intEx) {
                            // Ignore
                            }
                            hasKilledTransaction = transactionKiller.hasKilledTransaction;
                        }
                        // transaction killed by TransactionKiller is treated as PessimisticLockException
                        if (isExceptionExpected && !hasKilledTransaction) {
                            String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Exception was expected.";
                            broker.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, null, null, false);
                            errorMsg += '\n' + localErrorMsg;
                        }
                    } catch (Exception ex) {
                        if (transactionKiller != null) {
                            transactionKiller.shouldKillTransaction = false;
                            try {
                                transactionKiller.join();
                            } catch (InterruptedException intEx) {
                            // Ignore
                            }
                        }
                        if (!isExceptionExpected) {
                            String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Unexpected exception: " + ex.getMessage();
                            broker.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, null, null, false);
                            errorMsg += '\n' + localErrorMsg;
                        }
                    } finally {
                        if (isTransactionActive(em2)) {
                            rollbackTransaction(em2);
                        }
                        closeEntityManager(em2);
                    }
                // commitTransaction(em1);
                } finally {
                    if (isTransactionActive(em1)) {
                        rollbackTransaction(em1);
                    }
                    closeEntityManager(em1);
                }
                clearCache();
            }
        // testModel2 loop
        }
    // isObjectCached loop
    }
    // testMode1 loop
    // clean up
    em = createEntityManager();
    emp = em.find(Employee.class, id);
    try {
        beginTransaction(em);
        Iterator<Project> it = emp.getProjects().iterator();
        while (it.hasNext()) {
            Project project = it.next();
            it.remove();
            em.remove(project);
        }
        em.remove(emp);
        commitTransaction(em);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : SmallProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SmallProject) Query(jakarta.persistence.Query) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReportQuery(org.eclipse.persistence.queries.ReportQuery) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ValueReadQuery(org.eclipse.persistence.queries.ValueReadQuery) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery) TypedQuery(jakarta.persistence.TypedQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) HashMap(java.util.HashMap) SessionBroker(org.eclipse.persistence.sessions.broker.SessionBroker) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) TestProblemException(org.eclipse.persistence.testing.framework.TestProblemException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) EclipseLinkException(org.eclipse.persistence.exceptions.EclipseLinkException) EntityExistsException(jakarta.persistence.EntityExistsException) OptimisticLockException(jakarta.persistence.OptimisticLockException) RollbackException(jakarta.persistence.RollbackException) PersistenceException(jakarta.persistence.PersistenceException) QueryException(org.eclipse.persistence.exceptions.QueryException) TransactionRequiredException(jakarta.persistence.TransactionRequiredException) LargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SuperLargeProject) Project(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.Project) SmallProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SmallProject) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_2.Employee) LockModeType(jakarta.persistence.LockModeType) LargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.LargeProject) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.SuperLargeProject)

Aggregations

LockModeType (jakarta.persistence.LockModeType)12 EntityManager (jakarta.persistence.EntityManager)8 HashMap (java.util.HashMap)6 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)4 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)4 DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)3 EntityExistsException (jakarta.persistence.EntityExistsException)2 EntityNotFoundException (jakarta.persistence.EntityNotFoundException)2 OptimisticLockException (jakarta.persistence.OptimisticLockException)2 PersistenceException (jakarta.persistence.PersistenceException)2 Query (jakarta.persistence.Query)2 RollbackException (jakarta.persistence.RollbackException)2 TransactionRequiredException (jakarta.persistence.TransactionRequiredException)2 TypedQuery (jakarta.persistence.TypedQuery)2 EclipseLinkException (org.eclipse.persistence.exceptions.EclipseLinkException)2 IntegrityException (org.eclipse.persistence.exceptions.IntegrityException)2 QueryException (org.eclipse.persistence.exceptions.QueryException)2 ValidationException (org.eclipse.persistence.exceptions.ValidationException)2 JpaQuery (org.eclipse.persistence.jpa.JpaQuery)2 DataModifyQuery (org.eclipse.persistence.queries.DataModifyQuery)2