Search in sources :

Example 36 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class TestParameterBinding method testCOALESCE_ForceBindJPQLParameters.

@Test
public void testCOALESCE_ForceBindJPQLParameters() {
    EntityManager em = forceBindEMF.createEntityManager();
    try {
        // 1: Test COALESCE function with positional parameter and typed parameter
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 1 FROM GenericEntity s " + "WHERE ABS(COALESCE(s.itemInteger1, ?1)) >= ?2", GenericEntity.class);
        query.setParameter(1, 0);
        query.setParameter(2, 99);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number in the query", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 2, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 2: Test COALESCE function with literal and typed parameter
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 1 FROM GenericEntity s " + "WHERE ABS(COALESCE(s.itemInteger1, 0)) >= 99", GenericEntity.class);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 0, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 3: Test COALESCE function with all arguments as parameters
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 1 FROM GenericEntity s " + "WHERE ABS(COALESCE(?1, ?2)) >= ?3", GenericEntity.class);
        query.setParameter(1, 1);
        query.setParameter(2, 20);
        query.setParameter(3, 300);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.isDB2Z() || pl.isDerby()) {
            Assert.fail("Expected a failure from " + pl);
        }
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 4, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        }
    } catch (PersistenceException e) {
        Platform pl = forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.isDB2Z()) {
            // If all Arguments of COALESCE are untyped parameters, this is expected to fail for DB2/z
            Assert.assertEquals(DatabaseException.class, e.getCause().getClass());
            Assert.assertEquals("com.ibm.db2.jcc.am.SqlSyntaxErrorException", e.getCause().getCause().getClass().getName());
        } else if (pl.isDB2()) {
            // If all Arguments of COALESCE are untyped parameters, this is expected to fail for DB2 LUW
            Assert.assertEquals(DatabaseException.class, e.getCause().getClass());
        } else if (pl.isDerby()) {
            // All the arguments to the COALESCE/VALUE function cannot be parameters.
            // The function needs at least one argument that is not a parameter. Error 42610.
            Assert.assertEquals(DatabaseException.class, e.getCause().getClass());
            Assert.assertEquals("java.sql.SQLSyntaxErrorException", e.getCause().getCause().getClass().getName());
        } else {
            Assert.fail("Unexpected failure: " + e);
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) Platform(org.eclipse.persistence.internal.databaseaccess.Platform) GenericEntity(org.eclipse.persistence.jpa.test.property.model.GenericEntity) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) Test(org.junit.Test)

Example 37 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class TestParameterBinding method testABS_ForceBindJPQLParameters.

@Test
public void testABS_ForceBindJPQLParameters() {
    EntityManager em = forceBindEMF.createEntityManager();
    try {
        // 1: Test ABS function with parameter
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 2, COUNT(ABS(?1)) FROM GenericEntity s " + "WHERE s.itemInteger1 = ABS(?1)", GenericEntity.class);
        query.setParameter(1, -3);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.isDB2Z()) {
            Assert.fail("Expected a failure from " + pl);
        }
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 2, call.getParameters().size());
        }
    } catch (PersistenceException e) {
        Platform pl = forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        // ABS is a built-in function and built-in functions do not support untyped parameters on DB2/z
        if (pl.isDB2Z()) {
            Assert.assertEquals(DatabaseException.class, e.getCause().getClass());
            Assert.assertEquals("com.ibm.db2.jcc.am.SqlSyntaxErrorException", e.getCause().getCause().getClass().getName());
        } else {
            Assert.fail("Unexpected failure: " + e);
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 2: Test ABS function with literal
        TypedQuery<GenericEntity> query = em.createQuery("SELECT 2, COUNT(ABS(-3)) FROM GenericEntity s " + "WHERE s.itemInteger1 = ABS(-3)", GenericEntity.class);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 0, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) Platform(org.eclipse.persistence.internal.databaseaccess.Platform) GenericEntity(org.eclipse.persistence.jpa.test.property.model.GenericEntity) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) Test(org.junit.Test)

Example 38 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class TestParameterBinding method testEXISTS_ForceBindJPQLParameters.

@Test
public void testEXISTS_ForceBindJPQLParameters() {
    EntityManager em = forceBindEMF.createEntityManager();
    try {
        // 9: Test string parameter in sub query
        TypedQuery<GenericEntity> query = em.createQuery("SELECT s FROM GenericEntity s " + "WHERE s.itemString1 = ?1  AND EXISTS (SELECT 1 FROM GenericEntity e WHERE s.itemInteger1 = ?2 )", GenericEntity.class);
        query.setParameter(1, "Test");
        query.setParameter(2, 33);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 2, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
    em = forceBindEMF.createEntityManager();
    try {
        // 10: Test string literal in sub query
        TypedQuery<GenericEntity> query = em.createQuery("SELECT s FROM GenericEntity s " + "WHERE s.itemString1 = 'Test' AND EXISTS (SELECT 1 FROM GenericEntity e WHERE s.itemInteger1 = 33 )", GenericEntity.class);
        query.getResultList();
        DatabaseCall call = ((JpaQuery<GenericEntity>) query).getDatabaseQuery().getCall();
        Assert.assertFalse("Expected query parameter binding to not be set for the DatabaseCall", call.isUsesBindingSet());
        DatabasePlatform pl = (DatabasePlatform) forceBindEMF.unwrap(EntityManagerFactoryImpl.class).getDatabaseSession().getDatasourcePlatform();
        if (pl.shouldBindLiterals()) {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 3, call.getParameters().size());
        } else {
            Assert.assertEquals("The number of parameters found does not match the number supplied", 0, call.getParameters().size());
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) GenericEntity(org.eclipse.persistence.jpa.test.property.model.GenericEntity) EntityManagerFactoryImpl(org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) Test(org.junit.Test)

Example 39 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform in project eclipselink by eclipse-ee4j.

the class EmployeePopulator method persistExample.

public void persistExample(Session session) {
    Vector allObjects = new Vector();
    UnitOfWork unitOfWork = session.acquireUnitOfWork();
    // unitOfWork.removeAllReadOnlyClasses();
    PopulationManager.getDefaultManager().addAllObjectsForClass(Employee.class, allObjects);
    PopulationManager.getDefaultManager().addAllObjectsForClass(SmallProject.class, allObjects);
    PopulationManager.getDefaultManager().addAllObjectsForClass(LargeProject.class, allObjects);
    PopulationManager.getDefaultManager().addAllObjectsForClass(Runner.class, allObjects);
    unitOfWork.registerAllObjects(allObjects);
    unitOfWork.commit();
    DatabasePlatform platform = session.getLogin().getPlatform();
    if (TestCase.supportsStoredProcedures(session)) {
        boolean orig_FAST_TABLE_CREATOR = SchemaManager.FAST_TABLE_CREATOR;
        // of an instance of this class (drops & re-)creates the tables.
        if (useFastTableCreatorAfterInitialCreate && !isFirstCreation) {
            SchemaManager.FAST_TABLE_CREATOR = true;
        }
        try {
            SchemaManager schema = new SchemaManager((DatabaseSession) session);
            schema.replaceObject(buildStoredProcedureParameterTest(platform));
            schema.replaceObject(buildStoredProcedureReadFromAddress(platform));
            schema.replaceObject(buildStoredProcedureReadFromAddressMappedNamed(platform));
            schema.replaceObject(buildStoredProcedureReadFromAddressMappedNumbered(platform));
            schema.replaceObject(buildStoredProcedureUpdateFromAddress(platform));
            schema.replaceObject(buildStoredProcedureResultSetAndUpdateFromAddress(platform));
            schema.replaceObject(buildStoredProcedureReadAllAddresses());
            schema.replaceObject(buildStoredProcedureReadAllEmployees());
            schema.replaceObject(buildStoredProcedureReadAddressCity(platform));
            schema.replaceObject(buildStoredProcedureDeleteAllResponsibilities());
            if (platform.isOracle()) {
                schema.replaceObject(buildOraclePackage());
                schema.replaceObject(buildStoredProcedureReadUsingNamedRefCursor());
                schema.replaceObject(buildStoredProcedureReadUsingPosRefCursor());
                schema.replaceObject(buildStoredProcedureReadUsingSysCursor());
            }
            if (platform.isMySQL()) {
                schema.replaceObject(buildMySQLResultSetProcedure());
                schema.replaceObject(buildStoredProcedureReadNoAddresses());
            }
        } finally {
            if (useFastTableCreatorAfterInitialCreate && !isFirstCreation) {
                SchemaManager.FAST_TABLE_CREATOR = orig_FAST_TABLE_CREATOR;
            }
        }
        // next time it deletes the rows instead.
        isFirstCreation = false;
    }
    // Force uppercase for Postgres.
    if (platform.isPostgreSQL()) {
        session.getLogin().setShouldForceFieldNamesToUpperCase(true);
    }
}
Also used : UnitOfWork(org.eclipse.persistence.sessions.UnitOfWork) DatabasePlatform(org.eclipse.persistence.internal.databaseaccess.DatabasePlatform) SchemaManager(org.eclipse.persistence.tools.schemaframework.SchemaManager) Vector(java.util.Vector)

Example 40 with DatabasePlatform

use of org.eclipse.persistence.internal.databaseaccess.DatabasePlatform 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

DatabasePlatform (org.eclipse.persistence.internal.databaseaccess.DatabasePlatform)52 EntityManager (jakarta.persistence.EntityManager)12 DatabaseCall (org.eclipse.persistence.internal.databaseaccess.DatabaseCall)11 DatabaseException (org.eclipse.persistence.exceptions.DatabaseException)9 EntityManagerFactoryImpl (org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl)9 Test (org.junit.Test)9 GenericEntity (org.eclipse.persistence.jpa.test.property.model.GenericEntity)8 PersistenceException (jakarta.persistence.PersistenceException)6 Platform (org.eclipse.persistence.internal.databaseaccess.Platform)6 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)6 ResultSetMetaData (java.sql.ResultSetMetaData)5 DatabaseAccessor (org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor)5 FieldTypeDefinition (org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition)5 UnitOfWork (org.eclipse.persistence.sessions.UnitOfWork)5 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Vector (java.util.Vector)4