Search in sources :

Example 21 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("fieldaccess");
    beginTransaction(em);
    try {
        EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllFieldAccessEmployeesByFirstName");
        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("fieldaccess");
            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) Employee(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Employee) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Example 22 with EJBQueryImpl

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

the class AdvancedJPAJunitTest method testRemoveJillWithPrivateOwnedPhoneNumbers.

/**
 * Tests a @PrivateOwned @OneToMany mapping.
 */
public void testRemoveJillWithPrivateOwnedPhoneNumbers() {
    if (getServerSession("fieldaccess").getPlatform().isSymfoware()) {
        getServerSession("fieldaccess").logMessage("Test testRemoveJillWithPrivateOwnedPhoneNumbers skipped for this platform, " + "The CascadeOnDelete doesn't work on a relation where CascadeType.Remove or CascadeType.All is specified on Symfoware Platform.");
        return;
    }
    EntityManager em = createEntityManager("fieldaccess");
    beginTransaction(em);
    try {
        EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllFieldAccessEmployeesByFirstName");
        query.setParameter("firstname", "Jill");
        Collection<Employee> employees = query.getResultCollection();
        if (employees.isEmpty()) {
            fail("No employees named Jill were found. Test requires at least one Jill to be created in the EmployeePopulator.");
        } else {
            Employee jill = employees.iterator().next();
            Collection<PhoneNumber> phoneNumbers = jill.getPhoneNumbers();
            if (phoneNumbers.isEmpty()) {
                fail("Jill does not have any phone numbers. Test requires that Jill have atleast one phone number created in the EmployeePopulator.");
            }
            // Re-assign her managed employees and remove from her list.
            for (Employee employee : jill.getManagedEmployees()) {
                employee.setManager(jill.getManager());
            }
            jill.getManagedEmployees().clear();
            int jillId = jill.getId();
            em.remove(jill);
            commitTransaction(em);
            assertNull("Jill herself was not removed.", em.find(Employee.class, jillId));
            for (PhoneNumber phoneNumber : phoneNumbers) {
                assertNull("Jill's phone numbers were not deleted.", em.find(PhoneNumber.class, phoneNumber.buildPK()));
            }
        }
    } 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) Employee(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.Employee) PhoneNumber(org.eclipse.persistence.testing.models.jpa.fieldaccess.advanced.PhoneNumber) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Example 23 with EJBQueryImpl

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

the class EntityManagerTLRJUnitTestSuite method testQueryHints.

public void testQueryHints() {
    EntityManager em = getEntityManagerFactory("fieldaccess").createEntityManager();
    Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = 'testQueryHints'");
    ObjectLevelReadQuery olrQuery = (ObjectLevelReadQuery) ((EJBQueryImpl) 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());
    // 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());
    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());
    query.setHint(QueryHints.JDBC_TIMEOUT, 100);
    assertTrue("Timeout not set.", olrQuery.getQueryTimeout() == 100);
    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.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);
    query.setHint(QueryHints.RESULT_COLLECTION_TYPE, java.util.ArrayList.class);
    assertTrue("ArrayList not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().getContainerClassName().equals(java.util.ArrayList.class.getName()));
    query.setHint(QueryHints.RESULT_COLLECTION_TYPE, "java.util.Vector");
    assertTrue("Vector not set.", ((ReadAllQuery) olrQuery).getContainerPolicy().getContainerClassName().equals(java.util.Vector.class.getName()));
    closeEntityManager(em);
}
Also used : ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Query(jakarta.persistence.Query) ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl)

Example 24 with EJBQueryImpl

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

the class CriteriaQueryTestSuite method testOnClauseCompareSQL.

/**
 * This test verifies that the SQL generated for a criteria query with joins and an on clause matches
 * the SQL generated for the equivalent JPQL query, to ensure that excess table joins are not occurring that do
 * not affect the results.
 */
public void testOnClauseCompareSQL() {
    EntityManager em = createEntityManager();
    JpaEntityManager jpaEM = JpaHelper.getEntityManager((EntityManager) em.getDelegate());
    EJBQueryImpl query = (EJBQueryImpl) jpaEM.createQuery("Select e from Employee e left join e.manager m left join m.address a on a.city = 'Ottawa' " + "where a.postalCode is not null");
    String baseSQL = query.getDatabaseQuery().getTranslatedSQLString(this.getDatabaseSession(), new org.eclipse.persistence.sessions.DatabaseRecord());
    CriteriaBuilder qb = jpaEM.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
    Root<Employee> root = cq.from(Employee.class);
    Join<Object, Object> address = root.join("manager", JoinType.LEFT).join("address", JoinType.LEFT);
    address.on(qb.equal(address.get("city"), "Ottawa"));
    cq.where(qb.isNotNull(address.get("postalCode")));
    EJBQueryImpl testQuery = (EJBQueryImpl) jpaEM.createQuery(cq);
    String testSQL = testQuery.getDatabaseQuery().getTranslatedSQLString(this.getDatabaseSession(), new org.eclipse.persistence.sessions.DatabaseRecord());
    closeEntityManager(em);
    if (!testSQL.equals(baseSQL)) {
        fail("Criteria query using ON clause did not match SQL used for a JPQL query; generated SQL was: \"" + testSQL + "\"  but we expected: \"" + baseSQL + "\"");
    }
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa22.advanced.Employee)

Example 25 with EJBQueryImpl

use of org.eclipse.persistence.internal.jpa.EJBQueryImpl in project jmix by jmix-framework.

the class JmixEclipseLinkQuery method preExecute.

private void preExecute(JpaQuery<E> jpaQuery) {
    // copying behaviour of org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery()
    DatabaseQuery elDbQuery = ((EJBQueryImpl) jpaQuery).getDatabaseQueryInternal();
    boolean isObjectLevelReadQuery = elDbQuery.isObjectLevelReadQuery();
    if (jpaQuery.getFlushMode() == FlushModeType.AUTO && (!isObjectLevelReadQuery || !((ObjectLevelReadQuery) elDbQuery).isReadOnly())) {
        // flush is expected
        support.processFlush(entityManager, true);
        entityChangedEventManager.beforeFlush(support.getInstances(entityManager));
    }
}
Also used : ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) 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