Search in sources :

Example 26 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.models.jpa.relationships.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 : ReportQuery(org.eclipse.persistence.queries.ReportQuery) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) Query(jakarta.persistence.Query) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ValueReadQuery(org.eclipse.persistence.queries.ValueReadQuery) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery) TypedQuery(jakarta.persistence.TypedQuery) 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) CustomerCollection(org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) PhoneNumber(org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber) FetchGroup(org.eclipse.persistence.queries.FetchGroup) CursoredStreamPolicy(org.eclipse.persistence.queries.CursoredStreamPolicy) Vector(java.util.Vector) DataModifyQuery(org.eclipse.persistence.queries.DataModifyQuery)

Example 27 with EJBQueryImpl

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

the class RelationshipModelJUnitTestSuite method testGetSingleResultTest.

/*
     * Tests using the 'getSingleResult' api on a Query object obtained from the
     * EntityManager Tests fixes for bugs 4202835 and 4301674
     *
     * modified for changes in bug:4628215 (EntityNotFoundException)
     * EntityNotFoundException changed to NoResultException as per new spec
     */
public void testGetSingleResultTest() {
    // used for verification
    Customer returnedCustomer1, returnedCustomer2 = null;
    NonUniqueResultException expectedException1 = null;
    NoResultException expectedException2 = null;
    String searchString = "notAnItemName";
    Integer[] cusIDs = new Integer[3];
    Customer cusClone1 = RelationshipsExamples.customerExample1();
    Customer cusClone2 = RelationshipsExamples.customerExample2();
    EntityManager em = createEntityManager("fieldaccess");
    try {
        beginTransaction(em);
        em.persist(cusClone1);
        em.persist(cusClone2);
        commitTransaction(em);
        clearCache("fieldaccess");
        cusIDs[0] = cusClone1.getCustomerId();
        cusIDs[1] = cusClone2.getCustomerId();
        beginTransaction(em);
        try {
            returnedCustomer1 = (Customer) em.createNamedQuery("findAllCustomersFieldAccess").getSingleResult();
        } catch (NonUniqueResultException exceptionExpected1) {
            expectedException1 = exceptionExpected1;
        }
        try {
            // should be no Items to find, which should cause an
            // NoResultException
            Query query1 = em.createNamedQuery("findAllFieldAccessItemsByName");
            Item item = (Item) query1.setParameter(1, searchString).getSingleResult();
            item.toString();
        } catch (NoResultException exceptionExpected2) {
            expectedException2 = exceptionExpected2;
        }
        // bug 4301674 test
        EJBQueryImpl query2 = (EJBQueryImpl) em.createNamedQuery("findAllCustomersFieldAccess");
        ReadAllQuery readAllQuery = new ReadAllQuery(Customer.class);
        MapContainerPolicy mapContainerPolicy = new MapContainerPolicy();
        mapContainerPolicy.setContainerClass(HashMap.class);
        mapContainerPolicy.setKeyName("hashCode");
        readAllQuery.setContainerPolicy(mapContainerPolicy);
        query2.setDatabaseQuery(readAllQuery);
        Map result = (Map) query2.getSingleResult();
        result.toString();
        // check for single result found.
        Query query3 = em.createQuery("SELECT OBJECT(thecust) FROM FieldAccessCustomer thecust WHERE thecust.customerId = :id");
        returnedCustomer1 = (Customer) query3.setParameter("id", cusIDs[0]).getSingleResult();
        // check for single result using a ReadObjectQuery (tests previous
        // fix for 4202835)
        EJBQueryImpl query4 = (EJBQueryImpl) em.createQuery("SELECT OBJECT(thecust) FROM FieldAccessCustomer thecust WHERE thecust.customerId = :id");
        query4.setParameter("id", cusIDs[0]);
        ReadObjectQuery readObjectQuery = new ReadObjectQuery(Customer.class);
        readObjectQuery.setEJBQLString("SELECT OBJECT(thecust) FROM FieldAccessCustomer thecust WHERE thecust.customerId = :id");
        query4.setDatabaseQuery(readObjectQuery);
        returnedCustomer2 = (Customer) query4.getSingleResult();
        commitTransaction(em);
        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);
        if (expectedException1 == null) {
            fail("getSingelResult on query returning multiple values did not throw a NonUniqueResultException");
        }
        if (expectedException2 == null) {
            fail("getSingelResult on query returning multiple values did not throw an NoResultException");
        }
        if (returnedCustomer1 == null || (!returnedCustomer1.getCustomerId().equals(cusIDs[0]))) {
            fail("Incorrect Single Customer returned, found: " + returnedCustomer1);
        }
        if (returnedCustomer2 == null || (!returnedCustomer2.getCustomerId().equals(cusIDs[0]))) {
            fail("Incorrect Single Customer returned, found: " + returnedCustomer2);
        }
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
    }
}
Also used : NonUniqueResultException(jakarta.persistence.NonUniqueResultException) 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.fieldaccess.relationships.Customer) MapContainerPolicy(org.eclipse.persistence.internal.queries.MapContainerPolicy) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) NoResultException(jakarta.persistence.NoResultException) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) Item(org.eclipse.persistence.testing.models.jpa.fieldaccess.relationships.Item) EntityManager(jakarta.persistence.EntityManager) HashMap(java.util.HashMap) Map(java.util.Map)

Example 28 with EJBQueryImpl

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

the class AdvancedJPAJunitTest method testEmployeeToProjectWithBatchFetchTypeInRandomIteration.

/**
 * Bug 412056
 * Test batch fetch with size one less than results in random order
 */
public void testEmployeeToProjectWithBatchFetchTypeInRandomIteration() {
    final String lastName = "testRandomEmployeeToProject";
    // Set up
    Set<Employee> employeesToRemove = new HashSet<>();
    EntityManager em = createEntityManager();
    for (int i = 0; i < 100; i++) {
        beginTransaction(em);
        Employee employee = new Employee();
        employee.setLastName(lastName);
        employeesToRemove.add(employee);
        em.persist(employee);
        for (int j = 0; j < 20; j++) {
            Project project = new Project();
            employee.addProject(project);
            em.persist(project);
        }
        commitTransaction(em);
    }
    JpaEntityManager jpaEntityManager = (JpaEntityManager) em.getDelegate();
    jpaEntityManager.getUnitOfWork().getIdentityMapAccessor().initializeAllIdentityMaps();
    try {
        Expression exp = new ExpressionBuilder(Employee.class).get("lastName").equal(lastName);
        EJBQueryImpl query = (EJBQueryImpl) jpaEntityManager.createQuery(exp, Employee.class);
        ((ReadAllQuery) query.getDatabaseQuery()).addBatchReadAttribute("projects");
        ((ReadAllQuery) query.getDatabaseQuery()).setBatchFetchType(BatchFetchType.IN);
        ((ReadAllQuery) query.getDatabaseQuery()).setBatchFetchSize(99);
        List<Employee> employees = query.getResultList();
        // Trigger the bug
        Collections.shuffle(employees);
        int count = 0;
        try {
            for (Employee employee : employees) {
                for (Project project : employee.getProjects()) {
                    count++;
                }
            }
            Assert.assertEquals("Project objects received are not as many as expected", 2000, count);
        } catch (ArrayIndexOutOfBoundsException x) {
            Assert.fail(Helper.printStackTraceToString(x));
        }
    } finally {
        // Clean up
        beginTransaction(em);
        for (Employee employee : employeesToRemove) {
            employee = em.merge(employee);
            for (Project project : employee.getProjects()) {
                em.remove(em.merge(project));
            }
            em.remove(employee);
        }
        commitTransaction(em);
        closeEntityManager(em);
    }
}
Also used : JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) Project(org.eclipse.persistence.testing.models.jpa.advanced.Project) HugeProject(org.eclipse.persistence.testing.models.jpa.advanced.HugeProject) SmallProject(org.eclipse.persistence.testing.models.jpa.advanced.SmallProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) Expression(org.eclipse.persistence.expressions.Expression) HashSet(java.util.HashSet)

Example 29 with EJBQueryImpl

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

the class AdvancedJPAJunitTest method testAddNewEquipmentToDepartment.

/**
 * Tests adding objects to a 1-M mapping that uses a map.
 */
public void testAddNewEquipmentToDepartment() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllSQLEquipment");
        Collection<Equipment> equipment = query.getResultCollection();
        if (equipment.isEmpty()) {
            fail("No Equipment was found. testCreateNewEquipment should have created new equipment and should have run before this test.");
        } else {
            Department department = new Department();
            department.setName("Department with equipment");
            for (Equipment e : equipment) {
                department.addEquipment(e);
            }
            em.persist(department);
            deptId = department.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) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) Equipment(org.eclipse.persistence.testing.models.jpa.advanced.Equipment) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Example 30 with EJBQueryImpl

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

the class AdvancedMultiTenantJunitTest method validateMafiaFamily707.

protected void validateMafiaFamily707(EntityManager em) {
    clearCache(getMULTI_TENANT_PU());
    em.clear();
    beginTransaction(em);
    em.setProperty("tenant.id", "707");
    em.setProperty(EntityManagerProperties.MULTITENANT_PROPERTY_DEFAULT, "707");
    MafiaFamily family = em.find(MafiaFamily.class, family707);
    assertNotNull("The Mafia Family with id: " + family707 + ", was not found", family);
    assertTrue("The Mafia Family had an incorrect number of tags [" + family.getTags().size() + "], expected [3]", family.getTags().size() == 3);
    assertNull("The Mafia Family with id: " + family007 + ", was found (when it should not have been)", em.find(MafiaFamily.class, family007));
    assertNull("The Mafia Family with id: " + family123 + ", was found (when it should not have been)", em.find(MafiaFamily.class, family123));
    assertFalse("No mafiosos part of 707 family", family.getMafiosos().isEmpty());
    // See if we can find any members of the other family.
    for (Integer id : family007Mafiosos) {
        assertNull("Found family 007 mafioso.", em.find(Mafioso.class, id));
    }
    // Query directly for the boss from the other family.
    Boss otherBoss = em.find(Boss.class, family007Mafiosos.get(0));
    assertNull("Found family 007 boss.", otherBoss);
    // See if we can find any contracts of the other family.
    for (Integer id : family007Contracts) {
        assertNull("Found family 007 contract.", em.find(Contract.class, id));
    }
    // Try deleting a contract from the 007 family.
    Query deleteQuery = em.createNamedQuery("DeleteContractByPrimaryKey");
    deleteQuery.setParameter("id", family007Contracts.get(0));
    int result = deleteQuery.executeUpdate();
    assertTrue("Was able to delete a contract from the 007 family", result == 0);
    // Update all our contract descriptions to be 'voided'
    Query updateAllQuery = em.createNamedQuery("UpdateAllContractDescriptions");
    updateAllQuery.executeUpdate();
    // Need to check that tenant id column is present
    assertTrue("Tenant discriminator column not found in update all query", ((EJBQueryImpl) updateAllQuery).getDatabaseQuery().getCall().getSQLString().contains("TENANT_ID"));
    // Read and validate the contracts
    List<Contract> contracts = em.createNamedQuery("FindAllContracts").getResultList();
    int contractNumber = contracts.size();
    assertTrue("Incorrect number of contracts were returned [" + contracts.size() + "], expected [3]", contracts.size() == 3);
    for (Contract contract : contracts) {
        assertTrue("Contract description was not voided.", contract.getDescription().equals("voided"));
    }
    // See how many soldiers are returned from a jpql query
    List soldiers = em.createQuery("SELECT s from Soldier s").getResultList();
    assertTrue("Incorrect number of soldiers were returned [" + soldiers.size() + "], expected [5]", soldiers.size() == 5);
    if (getServerSession(getMULTI_TENANT_PU()).getPlatform().isSymfoware()) {
        getServerSession(getMULTI_TENANT_PU()).logMessage("Test AdvancedMultiTenantJunitTest partially skipped for this platform, " + "which uses UpdateAll internally to check tenant-id when updating an entity using JOINED inheritance strategy. " + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
        commitTransaction(em);
        return;
    }
    // We know what the boss's id is for the 007 family to try to update him from the 707 pu.
    // The 007 family is validated after this test.
    Query query = em.createNamedQuery("UpdateBossName");
    query.setParameter("name", "Compromised");
    query.setParameter("id", family007Mafiosos.get(0));
    query.executeUpdate();
    commitTransaction(em);
}
Also used : Mafioso(org.eclipse.persistence.testing.models.jpa.advanced.multitenant.Mafioso) Boss(org.eclipse.persistence.testing.models.jpa.advanced.multitenant.Boss) Query(jakarta.persistence.Query) NamedQuery(jakarta.persistence.NamedQuery) TypedQuery(jakarta.persistence.TypedQuery) MafiaFamily(org.eclipse.persistence.testing.models.jpa.advanced.multitenant.MafiaFamily) List(java.util.List) ArrayList(java.util.ArrayList) Contract(org.eclipse.persistence.testing.models.jpa.advanced.multitenant.Contract) 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