Search in sources :

Example 11 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project eclipselink by eclipse-ee4j.

the class RelationshipModelJUnitTestSuite method testGetResultListTest.

/*
     * Tests using the 'getSingleResult' api on a Query object obtained from the
     * EntityManager Also tests bugs 4300879 - check non Collection container
     * policy error and 4297903 - check ReadObjectQuery fails
     */
public void testGetResultListTest() {
    Collection returnedCustomers1, returnedCustomers2;
    QueryException expectedException1 = null;
    String ejbql1 = "SELECT OBJECT(thecust) FROM Customer thecust WHERE thecust.customerId = :id";
    Integer[] cusIDs = new Integer[3];
    Customer cusClone1 = RelationshipsExamples.customerExample1();
    Customer cusClone2 = RelationshipsExamples.customerExample2();
    EntityManager em = createEntityManager();
    beginTransaction(em);
    em.persist(cusClone1);
    em.persist(cusClone2);
    commitTransaction(em);
    em.clear();
    clearCache();
    cusIDs[0] = cusClone1.getCustomerId();
    cusIDs[1] = cusClone2.getCustomerId();
    try {
        beginTransaction(em);
        EntityManagerImpl entityManagerImpl = (EntityManagerImpl) em.getDelegate();
        Query query1 = em.createNamedQuery("findAllCustomers");
        returnedCustomers1 = query1.getResultList();
        Query query2 = em.createQuery(ejbql1);
        query2.setParameter("id", -10);
        returnedCustomers2 = query2.getResultList();
        // bug:4297903, check container policy failure
        EJBQueryImpl query3 = (EJBQueryImpl) entityManagerImpl.createQuery(ejbql1);
        ReadAllQuery readAllQuery = new ReadAllQuery(Customer.class);
        MapContainerPolicy mapContainerPolicy = new MapContainerPolicy();
        mapContainerPolicy.setContainerClass(HashMap.class);
        mapContainerPolicy.setKeyName("hashCode");
        readAllQuery.setContainerPolicy(mapContainerPolicy);
        query3.setDatabaseQuery(readAllQuery);
        try {
            query3.getResultList();
        } catch (PersistenceException exc) {
            // QueryException.INVALID_CONTAINER_CLASS
            expectedException1 = (QueryException) exc.getCause();
            rollbackTransaction(em);
            beginTransaction(em);
        }
        entityManagerImpl = (EntityManagerImpl) em.getDelegate();
        // bug:4300879, check ReadObjectQuery fails
        EJBQueryImpl query4 = (EJBQueryImpl) entityManagerImpl.createQuery(ejbql1);
        query4.setParameter("id", -10);
        ReadObjectQuery readObjectQuery2 = new ReadObjectQuery(Customer.class);
        readObjectQuery2.setEJBQLString(ejbql1);
        query4.setDatabaseQuery(readObjectQuery2);
        query4.getResultList();
        commitTransaction(em);
        if (returnedCustomers1 == null || (returnedCustomers1.size() < 2)) {
            fail("Not all customers were returned from findAllCustomers query ");
        }
        if (returnedCustomers2 == null || (returnedCustomers2.size() != 0)) {
            fail("Customer from ReadObjectQuery was not returned using getResultCollection");
        }
        if (expectedException1 == null || (expectedException1.getErrorCode() != QueryException.INVALID_CONTAINER_CLASS)) {
            fail("getResultCollection on query returning a hashtable did not throw expected INVALID_CONTAINER_CLASS QueryException");
        }
        beginTransaction(em);
        Customer cus1 = em.find(Customer.class, cusIDs[0]);
        em.remove(cus1);
        Customer cus2 = em.find(Customer.class, cusIDs[1]);
        em.remove(cus2);
        commitTransaction(em);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
    }
}
Also used : Query(jakarta.persistence.Query) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) Customer(org.eclipse.persistence.testing.models.jpa.relationships.Customer) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) MapContainerPolicy(org.eclipse.persistence.internal.queries.MapContainerPolicy) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) QueryException(org.eclipse.persistence.exceptions.QueryException) EntityManager(jakarta.persistence.EntityManager) PersistenceException(jakarta.persistence.PersistenceException) CustomerCollection(org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection) Collection(java.util.Collection)

Example 12 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project eclipselink by eclipse-ee4j.

the class PLSQLTestSuite method testOracleTypeProcessing.

/**
 * Test processing of OracleObject and OracleArray annotations.
 *
 * @see OracleArray
 * @see org.eclipse.persistence.platform.database.oracle.annotations.OracleObject
 */
public void testOracleTypeProcessing() {
    if (!getServerSession().getPlatform().isOracle()) {
        return;
    }
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        Query query = em.createNamedQuery("TEST_ORACLE_TYPES");
        assertNotNull("EntityManager could not create query [TEST_ORACLE_TYPES]", query);
        assertTrue("Expected EJBQueryImpl but was [" + query.getClass().getName() + "]", query instanceof EJBQueryImpl);
        DatabaseCall call = ((EJBQueryImpl) query).getDatabaseQuery().getCall();
        assertNotNull("The DatabaseCall was not set on the query", call);
        assertTrue("Expected PLSQLStoredProcedureCall but was [" + call.getClass().getName() + "]", call instanceof PLSQLStoredProcedureCall);
        PLSQLStoredProcedureCall plsqlCall = (PLSQLStoredProcedureCall) call;
        List<PLSQLargument> args = plsqlCall.getArguments();
        assertTrue("Expected 2 arguments, but was [" + args.size() + "]", args.size() == 2);
        boolean foundINArg = false;
        boolean foundOUTArg = false;
        for (PLSQLargument arg : args) {
            if (arg.name.equals("P_IN")) {
                foundINArg = true;
                assertNotNull("databaseType for arg P_IN is null", arg.databaseType);
                assertTrue("Expected arg P_IN to be an OracleArrayType, but was [" + arg.databaseType.getClass().getName() + "]", arg.databaseType instanceof OracleArrayType);
                OracleArrayType arrayType = (OracleArrayType) arg.databaseType;
                assertTrue("Expected arg P_IN to have databaseType set with type name VARRAY_NUMERO_UNO, but was [" + arrayType.getTypeName() + "]", arrayType.getTypeName().equals("VARRAY_NUMERO_UNO"));
                assertNotNull("Expected VARRAY_NUMERO_UNO to have nested type VARCHAR, but was null", arrayType.getNestedType());
                assertTrue("Expected VARRAY_NUMERO_UNO to have nested type VARCHAR, but was [" + arrayType.getNestedType().getTypeName() + "]", arrayType.getNestedType().getTypeName().equals("VARCHAR"));
            } else if (arg.name.equals("P_OUT")) {
                foundOUTArg = true;
                assertNotNull("databaseType for arg P_OUT is null", arg.databaseType);
                assertTrue("Expected arg P_OUT to be an OracleObjectType, but was [" + arg.databaseType.getClass().getName() + "]", arg.databaseType instanceof OracleObjectType);
                OracleObjectType objectType = (OracleObjectType) arg.databaseType;
                assertTrue("Expected arg P_OUT to have databaseType set with type name OBJECT_NUMERO_DOS, but was [" + objectType.getTypeName() + "]", objectType.getTypeName().equals("OBJECT_NUMERO_DOS"));
                assertTrue("Expected OBJECT_NUMERO_DOS to have 2 fields, but was [" + objectType.getFields().size() + "]", objectType.getFields().size() == 2);
                for (String key : objectType.getFields().keySet()) {
                    DatabaseType dbType = objectType.getFields().get(key);
                    if (key.equals("OO_FLD1")) {
                        assertTrue("Expected field OO_FLD1 to have databaseType NUMERIC, but was [" + dbType.getTypeName() + "]", dbType.getTypeName().equals("NUMERIC"));
                    } else if (key.equals("OO_FLD2")) {
                        assertTrue("Expected field OO_FLD2 to have databaseType NUMERIC, but was [" + dbType.getTypeName() + "]", dbType.getTypeName().equals("NUMERIC"));
                    } else {
                        fail("Expected OBJECT_NUMERO_DOS to have fields OO_FLD1 and OO_FLD2 but encountered field [" + key + "]");
                    }
                }
            } else {
                fail("Expected arg name to be one of P_IN or P_OUT, but was [" + arg.name + "]");
            }
        }
        assertTrue("IN arg P_IN was not processed", foundINArg);
        assertTrue("OUT arg P_OUT was not processed", foundOUTArg);
    } finally {
        closeEntityManagerAndTransaction(em);
    }
}
Also used : DatabaseCall(org.eclipse.persistence.internal.databaseaccess.DatabaseCall) EntityManager(jakarta.persistence.EntityManager) PLSQLStoredProcedureCall(org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall) Query(jakarta.persistence.Query) DatabaseType(org.eclipse.persistence.internal.helper.DatabaseType) OracleObjectType(org.eclipse.persistence.platform.database.oracle.jdbc.OracleObjectType) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) PLSQLargument(org.eclipse.persistence.platform.database.oracle.plsql.PLSQLargument) OracleArrayType(org.eclipse.persistence.platform.database.oracle.jdbc.OracleArrayType)

Example 13 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testQueryHints.

public void testQueryHints() {
    EntityManager em = (EntityManager) getEntityManagerFactory().createEntityManager().getDelegate();
    Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = 'testQueryHints'");
    // Set a hint first to trigger query clone (because query is accessed before other hints are set).
    query.setHint(QueryHints.READ_ONLY, false);
    ObjectLevelReadQuery olrQuery = (ObjectLevelReadQuery) ((JpaQuery) query).getDatabaseQuery();
    // binding
    // original state = default state
    assertTrue(olrQuery.shouldIgnoreBindAllParameters());
    // set boolean true
    query.setHint(QueryHints.BIND_PARAMETERS, true);
    // Parse cached query may be cloned when hint set, so re-get.
    olrQuery = (ObjectLevelReadQuery) ((EJBQueryImpl) query).getDatabaseQuery();
    assertTrue("Binding not set.", olrQuery.shouldBindAllParameters());
    // reset to original state
    query.setHint(QueryHints.BIND_PARAMETERS, "");
    assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
    // set "false"
    query.setHint(QueryHints.BIND_PARAMETERS, "false");
    assertFalse("Binding not set.", olrQuery.shouldBindAllParameters());
    // reset to the original state
    query.setHint(QueryHints.BIND_PARAMETERS, "");
    assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
    // cache usage
    query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
    assertTrue("Cache usage not set.", olrQuery.getCacheUsage() == ObjectLevelReadQuery.DoNotCheckCache);
    query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
    assertTrue("Cache usage not set.", olrQuery.shouldCheckCacheOnly());
    query.setHint(QueryHints.CACHE_USAGE, CacheUsage.ConformResultsInUnitOfWork);
    assertTrue("Cache usage not set.", olrQuery.shouldConformResultsInUnitOfWork());
    query.setHint(QueryHints.INDIRECTION_POLICY, CacheUsageIndirectionPolicy.Trigger);
    assertTrue("INDIRECTION_POLICY not set.", olrQuery.getInMemoryQueryIndirectionPolicyState() == InMemoryQueryIndirectionPolicy.SHOULD_TRIGGER_INDIRECTION);
    // reset to the original state
    query.setHint(QueryHints.CACHE_USAGE, "");
    assertTrue("Cache usage not set.", olrQuery.shouldCheckDescriptorForCacheUsage());
    // pessimistic lock
    query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock);
    assertTrue("Lock not set.", olrQuery.getLockMode() == ObjectLevelReadQuery.LOCK);
    query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.NoLock);
    assertTrue("Lock not set.", olrQuery.getLockMode() == ObjectLevelReadQuery.NO_LOCK);
    query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait);
    assertTrue("Lock not set.", olrQuery.getLockMode() == ObjectLevelReadQuery.LOCK_NOWAIT);
    // default state
    query.setHint(QueryHints.PESSIMISTIC_LOCK, "");
    assertTrue("Lock not set.", olrQuery.getLockMode() == ObjectLevelReadQuery.NO_LOCK);
    // refresh
    // set to original state - don't refresh.
    // the previously run LOCK and LOCK_NOWAIT have swithed it to true
    query.setHint(QueryHints.REFRESH, false);
    assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
    // set boolean true
    query.setHint(QueryHints.REFRESH, true);
    assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
    // check if cascade refresh is enabled
    assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping());
    // set "false"
    query.setHint(QueryHints.REFRESH, "false");
    assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
    // set Boolean.TRUE
    query.setHint(QueryHints.REFRESH, Boolean.TRUE);
    assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
    // check if cascade refresh is enabled
    assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping());
    // reset to original state
    query.setHint(QueryHints.REFRESH, "");
    assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
    // Read-only
    query.setHint(QueryHints.READ_ONLY, "false");
    assertFalse("Read-only not set.", olrQuery.isReadOnly());
    query.setHint(QueryHints.READ_ONLY, Boolean.TRUE);
    assertTrue("Read-only not set.", olrQuery.isReadOnly());
    query.setHint(QueryHints.READ_ONLY, Boolean.FALSE);
    assertFalse("Read-only not set.", olrQuery.isReadOnly());
    // Maintain cache
    query.setHint(QueryHints.MAINTAIN_CACHE, true);
    assertTrue("MAINTAIN_CACHE set.", olrQuery.shouldMaintainCache());
    query.setHint(QueryHints.MAINTAIN_CACHE, "false");
    assertFalse("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
    query.setHint(QueryHints.MAINTAIN_CACHE, Boolean.TRUE);
    assertTrue("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
    query.setHint(QueryHints.MAINTAIN_CACHE, Boolean.FALSE);
    assertFalse("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
    // Prepare
    query.setHint(QueryHints.PREPARE, true);
    assertTrue("PREPARE set.", olrQuery.shouldPrepare());
    query.setHint(QueryHints.PREPARE, "false");
    assertFalse("PREPARE not set.", olrQuery.shouldPrepare());
    query.setHint(QueryHints.PREPARE, Boolean.TRUE);
    assertTrue("PREPARE not set.", olrQuery.shouldPrepare());
    query.setHint(QueryHints.PREPARE, Boolean.FALSE);
    assertFalse("PREPARE not set.", olrQuery.shouldPrepare());
    // Cache statement
    query.setHint(QueryHints.CACHE_STATMENT, true);
    assertTrue("CACHE_STATMENT set.", olrQuery.shouldCacheStatement());
    query.setHint(QueryHints.CACHE_STATMENT, "false");
    assertFalse("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
    query.setHint(QueryHints.CACHE_STATMENT, Boolean.TRUE);
    assertTrue("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
    query.setHint(QueryHints.CACHE_STATMENT, Boolean.FALSE);
    assertFalse("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
    // Flush
    query.setHint(QueryHints.FLUSH, true);
    assertTrue("FLUSH set.", olrQuery.getFlushOnExecute());
    query.setHint(QueryHints.FLUSH, "false");
    assertFalse("FLUSH not set.", olrQuery.getFlushOnExecute());
    query.setHint(QueryHints.FLUSH, Boolean.TRUE);
    assertTrue("FLUSH not set.", olrQuery.getFlushOnExecute());
    query.setHint(QueryHints.FLUSH, Boolean.FALSE);
    assertFalse("FLUSH not set.", olrQuery.getFlushOnExecute());
    // Native connection
    query.setHint(QueryHints.NATIVE_CONNECTION, true);
    assertTrue("NATIVE_CONNECTION set.", olrQuery.isNativeConnectionRequired());
    query.setHint(QueryHints.NATIVE_CONNECTION, "false");
    assertFalse("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
    query.setHint(QueryHints.NATIVE_CONNECTION, Boolean.TRUE);
    assertTrue("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
    query.setHint(QueryHints.NATIVE_CONNECTION, Boolean.FALSE);
    assertFalse("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
    // Hint
    query.setHint(QueryHints.HINT, "/* use the index man */");
    assertTrue("HINT not set.", olrQuery.getHintString().equals("/* use the index man */"));
    // Cursor
    query.setHint(QueryHints.CURSOR, Boolean.TRUE);
    assertTrue("CURSOR not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isCursoredStreamPolicy());
    query.setHint(QueryHints.CURSOR, Boolean.FALSE);
    assertFalse("CURSOR set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isCursoredStreamPolicy());
    query.setHint(QueryHints.CURSOR_INITIAL_SIZE, "100");
    assertTrue("CURSOR not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isCursoredStreamPolicy());
    assertTrue("CURSOR_INITIAL_SIZE not set.", ((CursoredStreamPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getInitialReadSize() == 100);
    query.setHint(QueryHints.CURSOR_INITIAL_SIZE, 200);
    assertTrue("CURSOR_INITIAL_SIZE not set.", ((CursoredStreamPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getInitialReadSize() == 200);
    query.setHint(QueryHints.CURSOR, Boolean.FALSE);
    query.setHint(QueryHints.CURSOR_PAGE_SIZE, "100");
    assertTrue("CURSOR not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isCursoredStreamPolicy());
    assertTrue("CURSOR_PAGE_SIZE not set.", ((CursoredStreamPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getPageSize() == 100);
    query.setHint(QueryHints.CURSOR_PAGE_SIZE, 200);
    assertTrue("CURSOR_PAGE_SIZE not set.", ((CursoredStreamPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getPageSize() == 200);
    query.setHint(QueryHints.CURSOR, Boolean.FALSE);
    query.setHint(QueryHints.CURSOR_SIZE, "Select Count(*) from Employee");
    assertTrue("CURSOR_SIZE not set.", ((CursoredStreamPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getSizeQuery().getSQLString().equals("Select Count(*) from Employee"));
    // Scrollable cursor
    query.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.TRUE);
    assertTrue("SCROLLABLE_CURSOR not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isScrollableCursorPolicy());
    query.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.FALSE);
    assertFalse("SCROLLABLE_CURSOR set.", ((ReadAllQuery) olrQuery).getContainerPolicy().isScrollableCursorPolicy());
    query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.Reverse);
    assertTrue("RESULT_SET_TYPE not set.", ((ScrollableCursorPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getResultSetType() == ScrollableCursorPolicy.FETCH_REVERSE);
    query.setHint(QueryHints.RESULT_SET_CONCURRENCY, ResultSetConcurrency.Updatable);
    assertTrue("RESULT_SET_CONCURRENCY not set.", ((ScrollableCursorPolicy) ((ReadAllQuery) olrQuery).getContainerPolicy()).getResultSetConcurrency() == ScrollableCursorPolicy.CONCUR_UPDATABLE);
    // Exclusive connection
    query.setHint(QueryHints.EXCLUSIVE_CONNECTION, Boolean.TRUE);
    assertTrue("EXCLUSIVE_CONNECTION not set.", olrQuery.shouldUseExclusiveConnection());
    // Inheritance
    query.setHint(QueryHints.INHERITANCE_OUTER_JOIN, Boolean.TRUE);
    assertTrue("INHERITANCE_OUTER_JOIN not set.", olrQuery.shouldOuterJoinSubclasses());
    // History
    query.setHint(QueryHints.AS_OF, "1973/10/11 12:00:00");
    assertTrue("AS_OF not set.", olrQuery.getAsOfClause() != null);
    query.setHint(QueryHints.AS_OF_SCN, "12345");
    assertTrue("AS_OF_SCN not set.", ((Number) olrQuery.getAsOfClause().getValue()).intValue() == 12345);
    // Fetch groups
    query.setHint(QueryHints.FETCH_GROUP_DEFAULT, Boolean.FALSE);
    assertFalse("FETCH_GROUP_DEFAULT not set.", olrQuery.shouldUseDefaultFetchGroup());
    query.setHint(QueryHints.FETCH_GROUP_NAME, "nameAndCity");
    assertTrue("FETCH_GROUP_NAME not set.", olrQuery.getFetchGroupName().equals("nameAndCity"));
    query.setHint(QueryHints.FETCH_GROUP_ATTRIBUTE, "firstName");
    query.setHint(QueryHints.FETCH_GROUP_ATTRIBUTE, "lastName");
    assertTrue("FETCH_GROUP_ATTRIBUTE not set.", olrQuery.getFetchGroup().containsAttribute("firstName"));
    assertTrue("FETCH_GROUP_ATTRIBUTE not set.", olrQuery.getFetchGroup().containsAttribute("lastName"));
    FetchGroup fetchGroup = new FetchGroup();
    fetchGroup.addAttribute("id");
    query.setHint(QueryHints.FETCH_GROUP, fetchGroup);
    assertTrue("FETCH_GROUP not set.", olrQuery.getFetchGroup() == fetchGroup);
    // Timeout
    query.setHint(QueryHints.JDBC_TIMEOUT, 100);
    assertTrue("Timeout not set.", olrQuery.getQueryTimeout() == 100);
    // JDBC
    query.setHint(QueryHints.JDBC_FETCH_SIZE, 101);
    assertTrue("Fetch-size not set.", olrQuery.getFetchSize() == 101);
    query.setHint(QueryHints.JDBC_MAX_ROWS, 103);
    assertTrue("Max-rows not set.", olrQuery.getMaxRows() == 103);
    query.setHint(QueryHints.JDBC_FIRST_RESULT, 123);
    assertTrue("JDBC_FIRST_RESULT not set.", olrQuery.getFirstResult() == 123);
    // Refresh
    query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.NoCascading);
    assertTrue(olrQuery.getCascadePolicy() == DatabaseQuery.NoCascading);
    query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeByMapping);
    assertTrue(olrQuery.getCascadePolicy() == DatabaseQuery.CascadeByMapping);
    query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeAllParts);
    assertTrue(olrQuery.getCascadePolicy() == DatabaseQuery.CascadeAllParts);
    query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadePrivateParts);
    assertTrue(olrQuery.getCascadePolicy() == DatabaseQuery.CascadePrivateParts);
    // reset to the original state
    query.setHint(QueryHints.REFRESH_CASCADE, "");
    assertTrue(olrQuery.getCascadePolicy() == DatabaseQuery.CascadeByMapping);
    // Result collection
    query.setHint(QueryHints.RESULT_COLLECTION_TYPE, java.util.ArrayList.class);
    assertTrue("ArrayList not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().getContainerClass().equals(java.util.ArrayList.class));
    query.setHint(QueryHints.RESULT_COLLECTION_TYPE, "java.util.Vector");
    assertTrue("Vector not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().getContainerClass().equals(java.util.Vector.class));
    query.setHint(QueryHints.RESULT_COLLECTION_TYPE, "org.eclipse.persistence.testing.tests.jpa.composite.advanced.EntityManagerJUnitTestSuite$CustomerCollection");
    assertTrue("CustomerCollection not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().getContainerClass().equals(CustomerCollection.class));
    // Query type
    query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadObject);
    assertTrue("QUERY_TYPE not set.", ((JpaQuery) query).getDatabaseQuery().getClass().equals(ReadObjectQuery.class));
    query.setHint(QueryHints.QUERY_TYPE, QueryType.Report);
    assertTrue("QUERY_TYPE not set.", ((JpaQuery) query).getDatabaseQuery().getClass().equals(ReportQuery.class));
    query.setHint(QueryHints.QUERY_TYPE, QueryType.DataModify);
    assertTrue("QUERY_TYPE not set.", ((JpaQuery) query).getDatabaseQuery().getClass().equals(DataModifyQuery.class));
    query.setHint(QueryHints.QUERY_TYPE, "org.eclipse.persistence.queries.ValueReadQuery");
    assertTrue("QUERY_TYPE not set.", ((JpaQuery) query).getDatabaseQuery().getClass().equals(ValueReadQuery.class));
    query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadAll);
    assertTrue("QUERY_TYPE not set.", ((JpaQuery) query).getDatabaseQuery().getClass().equals(ReadAllQuery.class));
    // Result type
    query.setHint(QueryHints.QUERY_TYPE, QueryType.Report);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
    assertTrue("RESULT_TYPE not set.", ((ReportQuery) ((JpaQuery) query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnReportResult);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
    assertTrue("RESULT_TYPE not set.", ((ReportQuery) ((JpaQuery) query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnArray);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Value);
    assertTrue("RESULT_TYPE not set.", ((ReportQuery) ((JpaQuery) query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnSingleValue);
    query.setHint(QueryHints.QUERY_TYPE, QueryType.DataRead);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
    query.setHint(QueryHints.RESULT_TYPE, ResultType.Value);
    closeEntityManager(em);
}
Also used : 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) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReportQuery(org.eclipse.persistence.queries.ReportQuery) ValueReadQuery(org.eclipse.persistence.queries.ValueReadQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ArrayList(java.util.ArrayList) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) ScrollableCursorPolicy(org.eclipse.persistence.queries.ScrollableCursorPolicy) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) PhoneNumber(org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.PhoneNumber) FetchGroup(org.eclipse.persistence.queries.FetchGroup) CursoredStreamPolicy(org.eclipse.persistence.queries.CursoredStreamPolicy) Vector(java.util.Vector) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery)

Example 14 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project eclipselink by eclipse-ee4j.

the class AdvancedJPAJunitTest method testGiveFredAnObjectTypeConverterChange.

/**
 * Tests an ObjectTypeConverter on a direct to field mapping.
 */
public void testGiveFredAnObjectTypeConverterChange() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllEmployeesByFirstName");
        query.setParameter("firstname", "Fred");
        Collection<Employee> employees = query.getResultCollection();
        if (employees.isEmpty()) {
            fail("No employees named Fred were found. Test requires at least one Fred to be created in the EmployeePopulator.");
        } else {
            Employee fred = employees.iterator().next();
            fred.setFemale();
            fred.setFirstName("Penelope");
            penelopeId = fred.getId();
            commitTransaction(em);
            // Clear cache and clear the entity manager
            clearCache();
            em.clear();
            Employee penelope = em.find(Employee.class, penelopeId);
            assertTrue("Fred's ObjectTypeConverter change to Penelope didn't occur.", penelope.isFemale());
        }
    } catch (RuntimeException e) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
        // Re-throw exception to ensure stacktrace appears in test result.
        throw e;
    }
    closeEntityManager(em);
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Example 15 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project eclipselink by eclipse-ee4j.

the class AdvancedJPAJunitTest method testUpdateEmployee.

/**
 * Tests:
 * - BasicCollection mapping
 * - Serialized Basic of type EnumSet.
 * - BasicCollection that uses an Enum converter (by detection).
 */
public void testUpdateEmployee() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllSQLEmployees");
        Collection<Employee> employees = query.getResultCollection();
        if (employees.isEmpty()) {
            fail("No Employees were found. Test requires at least one Employee to be created in the EmployeePopulator.");
        } else {
            Employee emp = employees.iterator().next();
            emp.addResponsibility(newResponsibility);
            emp.setMondayToFridayWorkWeek();
            empId = emp.getId();
            commitTransaction(em);
        }
    } catch (RuntimeException e) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
        // Re-throw exception to ensure stacktrace appears in test result.
        throw e;
    }
    closeEntityManager(em);
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Aggregations

EJBQueryImpl (org.eclipse.persistence.internal.jpa.EJBQueryImpl)37 EntityManager (jakarta.persistence.EntityManager)31 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)19 Query (jakarta.persistence.Query)16 ReadAllQuery (org.eclipse.persistence.queries.ReadAllQuery)15 DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)12 ObjectLevelReadQuery (org.eclipse.persistence.queries.ObjectLevelReadQuery)8 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)8 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)6 MapContainerPolicy (org.eclipse.persistence.internal.queries.MapContainerPolicy)6 JpaQuery (org.eclipse.persistence.jpa.JpaQuery)6 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)6 List (java.util.List)5 PersistenceException (jakarta.persistence.PersistenceException)4 Collection (java.util.Collection)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 QueryException (org.eclipse.persistence.exceptions.QueryException)4 EntityManagerImpl (org.eclipse.persistence.internal.jpa.EntityManagerImpl)4 ReportQuery (org.eclipse.persistence.queries.ReportQuery)4