Search in sources :

Example 6 with LargeProject

use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testNestedBatchQueryHints.

public void testNestedBatchQueryHints() {
    String errorMsg = "";
    clearCache();
    ServerSession session = getServerSession();
    QuerySQLTracker counter = new QuerySQLTracker(session);
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        // setup
        int nEmployees = 2;
        int nProjects = 2;
        int nTeamMembers = 2;
        int nDealers = 2;
        int nPhones = 2;
        boolean useLargeProject = false;
        List<Employee> employees = new ArrayList(nEmployees);
        List<Employee> teamMembers = new ArrayList(nEmployees * nProjects * nTeamMembers);
        for (int i = 0; i < nEmployees; i++) {
            String iStr = Integer.toString(i);
            Employee emp = new Employee("Employee_NestedBatchQueryHint", iStr);
            employees.add(emp);
            Employee manager = new Employee("Manager_NestedBatchQueryHint", iStr);
            manager.addManagedEmployee(emp);
            for (int j = 0; j < nProjects; j++) {
                String jStr = Integer.toString(j);
                Project project;
                if (useLargeProject) {
                    project = new LargeProject();
                } else {
                    project = new SmallProject();
                }
                useLargeProject = !useLargeProject;
                project.setName(iStr + jStr);
                manager.addProject(project);
                project.addTeamMember(manager);
                for (int k = 0; k < nTeamMembers; k++) {
                    String kStr = Integer.toString(k);
                    String teamMemberLastName = iStr + jStr + kStr;
                    Employee teamMember = new Employee("TeamMember_NestedBatchQueryHint", teamMemberLastName);
                    teamMembers.add(teamMember);
                    teamMember.addProject(project);
                    project.addTeamMember(teamMember);
                    for (int l = 0; l < nDealers; l++) {
                        String lStr = Integer.toString(l);
                        Dealer dealer = new Dealer(lStr, teamMemberLastName);
                        teamMember.addDealer(dealer);
                    }
                    for (int l = 0; l < nPhones; l++) {
                        String lStr = Integer.toString(l);
                        PhoneNumber phone = new PhoneNumber(lStr, teamMemberLastName, lStr + lStr + lStr + lStr + lStr + lStr + lStr);
                        teamMember.addPhoneNumber(phone);
                    }
                }
            }
        }
        // Persist cacscaded manager, then projects
        for (Employee emp : employees) {
            em.persist(emp);
        }
        // Persist cacscaded dealers and phones
        for (Employee emp : teamMembers) {
            em.persist(emp);
        }
        em.flush();
        // test
        em.clear();
        Query query1 = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = 'Employee_NestedBatchQueryHint' ORDER BY e.lastName");
        query1.setHint(QueryHints.BATCH, "e.manager");
        query1.setHint(QueryHints.BATCH, "e.manager.projects");
        query1.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers");
        query1.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.dealers");
        query1.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.phoneNumbers");
        errorMsg += verifyBatchReading("query1", query1, counter, employees, session);
        em.clear();
        Query query2 = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = 'Employee_NestedBatchQueryHint' ORDER BY e.lastName");
        query2.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers");
        query2.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.dealers");
        query2.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.phoneNumbers");
        errorMsg += verifyBatchReading("query2", query2, counter, employees, session);
        em.clear();
        Query query3 = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = 'Employee_NestedBatchQueryHint' ORDER BY e.lastName");
        query3.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.dealers");
        query3.setHint(QueryHints.BATCH, "e.manager.projects.teamMembers.phoneNumbers");
        errorMsg += verifyBatchReading("query3", query3, counter, employees, session);
    } finally {
        // clean-up
        rollbackTransaction(em);
        closeEntityManager(em);
        counter.remove();
    }
    if (errorMsg.length() > 0) {
        fail(errorMsg);
    }
}
Also used : SmallProject(org.eclipse.persistence.testing.models.jpa.advanced.SmallProject) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) 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) ArrayList(java.util.ArrayList) QuerySQLTracker(org.eclipse.persistence.testing.framework.QuerySQLTracker) 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) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) SpecialHugeProject(org.eclipse.persistence.testing.models.jpa.advanced.SpecialHugeProject) 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) PhoneNumber(org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject) Dealer(org.eclipse.persistence.testing.models.jpa.advanced.Dealer)

Example 7 with LargeProject

use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method internalTestUpdateAllProjects.

protected void internalTestUpdateAllProjects(Class<?> cls) {
    if ((JUnitTestCase.getServerSession()).getPlatform().isSymfoware()) {
        getServerSession().logMessage("Test testUpdateAll*Projects skipped for this platform, " + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
        return;
    }
    String className = Helper.getShortClassName(cls);
    String name = "testUpdateAllProjects";
    String newName = "testUpdateAllProjectsNEW";
    HashMap map = null;
    boolean ok = false;
    try {
        // setup
        // save the original names of projects: will set them back in cleanup
        // to restore the original state.
        EntityManager em = createEntityManager();
        List projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
        map = new HashMap(projects.size());
        for (int i = 0; i < projects.size(); i++) {
            Project p = (Project) projects.get(i);
            map.put(p.getId(), p.getName());
        }
        // populate Projects - necessary only if no SmallProject and/or LargeProject objects already exist.
        beginTransaction(em);
        try {
            createProjectsWithName(name, null, em);
            commitTransaction(em);
        } finally {
            closeEntityManagerAndTransaction(em);
        }
        // test
        em = createEntityManager();
        beginTransaction(em);
        try {
            em.createQuery("UPDATE " + className + " p set p.name = '" + newName + "'").executeUpdate();
            commitTransaction(em);
        } finally {
            closeEntityManagerAndTransaction(em);
        }
        // verify
        em = createEntityManager();
        String errorMsg = "";
        try {
            projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
            for (int i = 0; i < projects.size(); i++) {
                Project p = (Project) projects.get(i);
                String readName = p.getName();
                if (cls.isInstance(p)) {
                    if (!newName.equals(readName)) {
                        errorMsg = errorMsg + "haven't updated name: " + p + "; ";
                    }
                } else {
                    if (newName.equals(readName)) {
                        errorMsg = errorMsg + "have updated name: " + p + "; ";
                    }
                }
            }
        } catch (RuntimeException ex) {
            if (usesSOP() && !isSOPRecoverable()) {
                if (ex instanceof PersistenceException) {
                    if (ex.getCause() instanceof QueryException && ((QueryException) ex.getCause()).getErrorCode() == QueryException.SOP_OBJECT_IS_NOT_FOUND) {
                    // getResultList is expected to fail because SOP field is set to null after bulk update
                    } else {
                        fail("Wrong cause of PersistenceException: " + ex.getCause());
                    }
                } else {
                    fail("PersistenceException was expected");
                }
            } else {
                throw ex;
            }
        } finally {
            closeEntityManager(em);
        }
        if (errorMsg.length() > 0) {
            fail(errorMsg);
        } else {
            ok = true;
        }
    } finally {
        // clean-up
        try {
            if (map != null) {
                EntityManager em = createEntityManager();
                beginTransaction(em);
                Query query = em.createQuery("SELECT OBJECT(p) FROM Project p");
                if (usesSOP() && !isSOPRecoverable()) {
                    // otherwise will fail because SOP field is set to null after bulk update
                    query.setHint(QueryHints.SERIALIZED_OBJECT, "false");
                }
                List projects = query.getResultList();
                try {
                    for (int i = 0; i < projects.size(); i++) {
                        Project p = (Project) projects.get(i);
                        String oldName = (String) map.get(((Project) projects.get(i)).getId());
                        p.setName(oldName);
                    }
                    commitTransaction(em);
                } finally {
                    closeEntityManagerAndTransaction(em);
                }
            }
            // delete projects that createProjectsWithName has created in setup.
            // these will be left over under the newName
            deleteProjectsWithName(newName);
        } catch (RuntimeException ex) {
            // eat clean-up exception in case the test failed
            if (ok) {
                throw ex;
            }
        }
    }
}
Also used : 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) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) SpecialHugeProject(org.eclipse.persistence.testing.models.jpa.advanced.SpecialHugeProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) QueryException(org.eclipse.persistence.exceptions.QueryException) 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) HashMap(java.util.HashMap) PersistenceException(jakarta.persistence.PersistenceException) IndirectList(org.eclipse.persistence.indirection.IndirectList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 8 with LargeProject

use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testLockWithJoinedInheritanceStrategy.

public void testLockWithJoinedInheritanceStrategy() throws InterruptedException {
    if (getServerSession().getPlatform().isMaxDB()) {
        // skip this test (bug 326799)
        return;
    }
    // Cannot create parallel entity managers in the server.
    if (!isOnServer() && isSelectForUpateNoWaitSupported()) {
        Employee emp = null;
        LargeProject largeProject = null;
        EntityManager em = createEntityManager();
        try {
            beginTransaction(em);
            emp = new Employee();
            largeProject = new LargeProject();
            largeProject.setName("Large Project");
            largeProject.setBudget(50000);
            emp.addProject(largeProject);
            em.persist(emp);
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            closeEntityManager(em);
            throw ex;
        }
        try {
            beginTransaction(em);
            emp = em.find(Employee.class, emp.getId());
            final Project lp1 = emp.getProjects().iterator().next();
            em.lock(lp1, LockModeType.PESSIMISTIC_WRITE);
            lp1.setName("Lock In Additional Table ");
            Runnable runnable = new Runnable() {

                @Override
                public void run() {
                    EntityManager em2 = createEntityManager();
                    try {
                        beginTransaction(em2);
                        LargeProject lp2 = em2.find(LargeProject.class, lp1.getId());
                        HashMap properties = new HashMap();
                        // According to the spec a 0 indicates a NOWAIT clause.
                        properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
                        em2.lock(lp2, LockModeType.PESSIMISTIC_WRITE, properties);
                    } catch (PersistenceException ex) {
                        if (!(ex instanceof jakarta.persistence.PessimisticLockException)) {
                            throw ex;
                        }
                    } finally {
                        rollbackTransaction(em2);
                        closeEntityManager(em2);
                    }
                }
            };
            Thread t2 = new Thread(runnable);
            t2.start();
            Thread.sleep(3000);
            // t2 should have failed to get a lock with NOWAIT and hence should have finished by now
            boolean hanging = t2.isAlive();
            if (hanging) {
                t2.interrupt();
            }
            commitTransaction(em);
            assertFalse("pessimistic lock with nowait on entity with joined inheritance causes concurrent thread to wait", hanging);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            throw ex;
        } finally {
            closeEntityManager(em);
        }
    } else {
        warning("Can't run this test because SELECT FOR UPDATE NO WAIT is not supported on this platform");
    }
}
Also used : 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) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) SpecialHugeProject(org.eclipse.persistence.testing.models.jpa.advanced.SpecialHugeProject) 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) HashMap(java.util.HashMap) PersistenceException(jakarta.persistence.PersistenceException) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)

Example 9 with LargeProject

use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.

the class EntityManagerJUnitTestSuite method testInheritanceQuery.

// bug 274975
public void testInheritanceQuery() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    LargeProject project = new LargeProject();
    em.persist(project);
    commitTransaction(em);
    int id = project.getId();
    clearCache();
    ClassDescriptor descriptor = getServerSession().getClassDescriptor(Project.class);
    ReadAllQuery query = new ReadAllQuery(Project.class);
    ExpressionBuilder b = query.getExpressionBuilder();
    // declare bind variable in (parent) query
    query.addArgument("id", Integer.class);
    ReportQuery subQuery = new ReportQuery();
    // use any dummy mapped class...
    subQuery.setReferenceClass(Project.class);
    SQLCall selectIdsCall = new SQLCall();
    // <= re-use bind variable in child query
    String subSelect = "select p.PROJ_ID from CMP3_PROJECT p where p.PROJ_ID = #id";
    selectIdsCall.setSQLString(subSelect);
    subQuery.setCall(selectIdsCall);
    Expression expr = b.get("id").in(subQuery);
    query.setSelectionCriteria(expr);
    // Now execute query with bind variable
    // (using setShouldBindAllParameters(false) makes it work...
    // but this is not good, in particular it prevents use of advanced queries with Oraclearrays as bind-variables!!!)
    Vector params = new Vector(1);
    params.add(id);
    List res = (List) getServerSession().executeQuery(query, params);
    assertTrue(res.size() == 1);
}
Also used : SQLCall(org.eclipse.persistence.queries.SQLCall) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) QueryKeyExpression(org.eclipse.persistence.internal.expressions.QueryKeyExpression) Expression(org.eclipse.persistence.expressions.Expression) ReportQuery(org.eclipse.persistence.queries.ReportQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) IndirectList(org.eclipse.persistence.indirection.IndirectList) ArrayList(java.util.ArrayList) List(java.util.List) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) Vector(java.util.Vector) SuperLargeProject(org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)

Example 10 with LargeProject

use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.

the class CriteriaQueryCastTestSuite method testDowncastInSelect.

public void testDowncastInSelect() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        LargeProject proj = new LargeProject();
        proj.setBudget(1000);
        proj.setName("test1");
        em.persist(proj);
        SmallProject sp = new SmallProject();
        sp.setName("sp1");
        em.persist(sp);
        em.flush();
        clearCache();
        em.clear();
        // this would work in the past if TYPE was added to the where clause
        // Query query = em.createQuery("Select treat(c as LargeProject).budget from Project c");
        CriteriaBuilder qb = em.getCriteriaBuilder();
        CriteriaQuery<Project> cq = qb.createQuery(Project.class);
        Root<Project> root = cq.from(Project.class);
        Root largeProjectRoot = qb.treat(root, LargeProject.class);
        cq.select(largeProjectRoot.get("budget"));
        List resultList = em.createQuery(cq).getResultList();
        assertTrue("Incorrect results returned", resultList.size() == 1);
    } finally {
        if (this.isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) SmallProject(org.eclipse.persistence.testing.models.jpa.advanced.SmallProject) Project(org.eclipse.persistence.testing.models.jpa.advanced.Project) SmallProject(org.eclipse.persistence.testing.models.jpa.advanced.SmallProject) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject) EntityManager(jakarta.persistence.EntityManager) Root(jakarta.persistence.criteria.Root) List(java.util.List) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)

Aggregations

LargeProject (org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)36 EntityManager (jakarta.persistence.EntityManager)33 SmallProject (org.eclipse.persistence.testing.models.jpa.advanced.SmallProject)24 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)23 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)22 List (java.util.List)15 Project (org.eclipse.persistence.testing.models.jpa.advanced.Project)14 SuperLargeProject (org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject)13 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)12 ReadAllQuery (org.eclipse.persistence.queries.ReadAllQuery)11 HugeProject (org.eclipse.persistence.testing.models.jpa.advanced.HugeProject)11 JpaQuery (org.eclipse.persistence.jpa.JpaQuery)9 ReportQuery (org.eclipse.persistence.queries.ReportQuery)9 SpecialHugeProject (org.eclipse.persistence.testing.models.jpa.advanced.SpecialHugeProject)9 Query (jakarta.persistence.Query)8 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)8 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 PersistenceException (jakarta.persistence.PersistenceException)4 TypedQuery (jakarta.persistence.TypedQuery)3