Search in sources :

Example 16 with Project

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

the class CriteriaQueryCastTestSuite method testDowncastManyToManyExpressionBuilder.

public void testDowncastManyToManyExpressionBuilder() {
    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);
        Employee emp = new Employee();
        emp.setFirstName("Reggie");
        emp.setLastName("Josephson");
        emp.addProject(proj);
        proj.addTeamMember(emp);
        emp.addProject(sp);
        sp.addTeamMember(emp);
        em.persist(emp);
        emp = new Employee();
        emp.setFirstName("Ron");
        emp.setLastName("Josephson");
        emp.addProject(sp);
        sp.addTeamMember(emp);
        em.persist(emp);
        em.flush();
        clearCache();
        em.clear();
        // JpaQuery query = (JpaQuery)em.createQuery("Select p from Project p where treat (p as LargeProject).budget > 100");
        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.where(qb.gt(largeProjectRoot.get("budget"), 100));
        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) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) Root(jakarta.persistence.criteria.Root) List(java.util.List) LargeProject(org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)

Example 17 with Project

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

the class EntityManagerJUnitTestSuite method testCascadeMergeDetached.

// Test cascade merge on a detached entity
public void testCascadeMergeDetached() {
    // setup
    Project p1 = new Project();
    p1.setName("Project1");
    Project p2 = new Project();
    p1.setName("Project2");
    Employee e1 = new Employee();
    e1.setFirstName("Employee1");
    Employee e2 = new Employee();
    e2.setFirstName("Employee2");
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        em.persist(p1);
        em.persist(p2);
        em.persist(e1);
        em.persist(e2);
        commitTransaction(em);
    } catch (RuntimeException re) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        throw re;
    }
    closeEntityManager(em);
    // end of setup
    // p1,p2,e1,e2 are detached
    // associate relationships
    // p1 -> e1 (one-to-one)
    p1.setTeamLeader(e1);
    // e1 -> e2 (one-to-many)
    e1.addManagedEmployee(e2);
    // e2 -> p2 (many-to-many)
    e2.addProject(p2);
    p2.addTeamMember(e2);
    em = createEntityManager();
    beginTransaction(em);
    try {
        // cascade merge
        Project mp1 = em.merge(p1);
        assertTrue(em.contains(mp1));
        assertTrue("Managed instance and detached instance must not be same", mp1 != p1);
        Employee me1 = mp1.getTeamLeader();
        assertTrue("Cascade merge failed", em.contains(me1));
        assertTrue("Managed instance and detached instance must not be same", me1 != e1);
        Employee me2 = me1.getManagedEmployees().iterator().next();
        assertTrue("Cascade merge failed", em.contains(me2));
        assertTrue("Managed instance and detached instance must not be same", me2 != e2);
        Project mp2 = me2.getProjects().iterator().next();
        assertTrue("Cascade merge failed", em.contains(mp2));
        assertTrue("Managed instance and detached instance must not be same", mp2 != p2);
        commitTransaction(em);
    } catch (RuntimeException re) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        throw re;
    }
    closeEntityManager(em);
}
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)

Example 18 with Project

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

the class EntityManagerJUnitTestSuite method testPersistenceProperties.

// The test removed because we moved back to binding literals
// on platforms other than DB2 and Derby
/*    public void testDontBindLiteral() {
        EntityManager em = createEntityManager();

        Query controlQuery = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT(:param1, :param2)");
        controlQuery.setParameter("param1", "A").setParameter("param2", "B");
        List controlResults = controlQuery.getResultList();
        int nControlParams = ((ExpressionQueryMechanism)((EJBQueryImpl)controlQuery).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
        if(nControlParams != 2) {
            fail("controlQuery has wrong number of parameters = "+nControlParams+"; 2 is expected");
        }

        Query query = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT('A', 'B')");
        List results = query.getResultList();
        int nParams = ((ExpressionQueryMechanism)((EJBQueryImpl)query).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
        if(nParams > 0) {
            fail("Query processed literals as parameters");
        }

        closeEntityManager(em);
    }*/
public void testPersistenceProperties() {
    // Different properties are used on the server.
    if (isOnServer()) {
        return;
    }
    EntityManager em = createEntityManager();
    ServerSession ss = ((org.eclipse.persistence.internal.jpa.EntityManagerImpl) em).getServerSession();
    // these properties were set in persistence unit
    // and overridden in CMP3TestModel.setup - the values should be overridden.
    boolean isReadShared = (ss.getReadConnectionPool() instanceof ReadConnectionPool);
    if (isReadShared != Boolean.parseBoolean((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED))) {
        fail("isReadShared is wrong");
    }
    int writeMin = ss.getDefaultConnectionPool().getMinNumberOfConnections();
    if (writeMin != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN))) {
        fail("writeMin is wrong");
    }
    int writeInitial = ss.getDefaultConnectionPool().getInitialNumberOfConnections();
    if (writeInitial != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_INITIAL))) {
        fail("writeInitial is wrong");
    }
    int writeMax = ss.getDefaultConnectionPool().getMaxNumberOfConnections();
    if (writeMax != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX))) {
        fail("writeMax is wrong");
    }
    int readMin = ss.getReadConnectionPool().getMinNumberOfConnections();
    if (readMin != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN))) {
        fail("readMin is wrong");
    }
    int readMax = ss.getReadConnectionPool().getMaxNumberOfConnections();
    if (readMax != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX))) {
        fail("readMax is wrong");
    }
    int batchSize = ss.getPlatform().getMaxBatchWritingSize();
    if (batchSize != Integer.parseInt((String) JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.BATCH_WRITING_SIZE))) {
        fail("batchSize is wrong");
    }
    // these properties were set in persistence unit - the values should be the same as in persistence.xml
    /*
            <property name="eclipselink.session-name" value="default-session"/>
            <property name="eclipselink.cache.size.default" value="500"/>
            <property name="eclipselink.cache.size.Employee" value="550"/>
            <property name="eclipselink.cache.size.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="555"/>
            <property name="eclipselink.cache.type.default" value="Full"/>
            <property name="eclipselink.cache.type.Employee" value="Weak"/>
            <property name="eclipselink.cache.type.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="HardWeak"/>
            <property name="eclipselink.session.customizer" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
            <property name="eclipselink.descriptor.customizer.Employee" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
            <property name="eclipselink.descriptor.customizer.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
            <property name="eclipselink.descriptor.customizer.Project" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
        */
    String sessionName = ss.getName();
    if (!sessionName.equals("default-session")) {
        fail("sessionName is wrong: " + sessionName);
    }
    int defaultCacheSize = ss.getDescriptor(Project.class).getIdentityMapSize();
    if (defaultCacheSize != 500) {
        fail("defaultCacheSize is wrong: " + defaultCacheSize);
    }
    int employeeCacheSize = ss.getDescriptor(Employee.class).getIdentityMapSize();
    if (employeeCacheSize != 550) {
        fail("employeeCacheSize is wrong: " + employeeCacheSize);
    }
    int addressCacheSize = ss.getDescriptor(Address.class).getIdentityMapSize();
    if (addressCacheSize != 555) {
        fail("addressCacheSize is wrong: " + addressCacheSize);
    }
    // Department cache size specified in @Cache annotation - that should override default property
    int departmentCacheSize = ss.getDescriptor(Department.class).getIdentityMapSize();
    if (departmentCacheSize != 777) {
        fail("departmentCacheSize is wrong: " + departmentCacheSize);
    }
    Class<?> defaultCacheType = ss.getDescriptor(Project.class).getIdentityMapClass();
    if (!Helper.getShortClassName(defaultCacheType).equals("FullIdentityMap")) {
        fail("defaultCacheType is wrong: " + Helper.getShortClassName(defaultCacheType));
    }
    Class<?> employeeCacheType = ss.getDescriptor(Employee.class).getIdentityMapClass();
    if (!Helper.getShortClassName(employeeCacheType).equals("WeakIdentityMap")) {
        fail("employeeCacheType is wrong: " + Helper.getShortClassName(employeeCacheType));
    }
    Class<?> addressCacheType = ss.getDescriptor(Address.class).getIdentityMapClass();
    if (!Helper.getShortClassName(addressCacheType).equals("HardCacheWeakIdentityMap")) {
        fail("addressCacheType is wrong: " + Helper.getShortClassName(addressCacheType));
    }
    // Department cache type specified in @Cache annotation - that should override default property
    Class<?> departmentCacheType = ss.getDescriptor(Department.class).getIdentityMapClass();
    if (!Helper.getShortClassName(departmentCacheType).equals("SoftCacheWeakIdentityMap")) {
        fail("departmentCacheType is wrong: " + Helper.getShortClassName(departmentCacheType));
    }
    int numSessionCalls = Customizer.getNumberOfCallsForSession(ss.getName());
    if (numSessionCalls == 0) {
        fail("session customizer hasn't been called");
    }
    int numProjectCalls = Customizer.getNumberOfCallsForClass(Project.class.getName());
    if (numProjectCalls == 0) {
        fail("Project customizer hasn't been called");
    }
    int numEmployeeCalls = Customizer.getNumberOfCallsForClass(Employee.class.getName());
    if (numEmployeeCalls == 0) {
        fail("Employee customizer hasn't been called");
    }
    int numAddressCalls = Customizer.getNumberOfCallsForClass(Address.class.getName());
    if (numAddressCalls == 0) {
        fail("Address customizer hasn't been called");
    }
    IdValidation employeeIdValidation = ss.getDescriptor(Employee.class).getIdValidation();
    if (employeeIdValidation != IdValidation.ZERO) {
        fail("employeeIdValidation is wrong, IdValidation.ZERO assigned through PrimaryKey annotation was expected");
    }
    IdValidation addressIdValidation = ss.getDescriptor(Address.class).getIdValidation();
    if (addressIdValidation != IdValidation.NEGATIVE) {
        fail("addressIdValidation is wrong, IdValidation.NEGATIVE set as a default value in persistence.xml was expected");
    }
    closeEntityManager(em);
}
Also used : ServerSession(org.eclipse.persistence.sessions.server.ServerSession) IdValidation(org.eclipse.persistence.annotations.IdValidation) ReadConnectionPool(org.eclipse.persistence.sessions.server.ReadConnectionPool) Address(org.eclipse.persistence.testing.models.jpa.advanced.Address) EntityManagerImpl(org.eclipse.persistence.internal.jpa.EntityManagerImpl) 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) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee)

Example 19 with Project

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

the class EntityManagerJUnitTestSuite method verifyBatchReading.

protected String verifyBatchReading(String queryName, Query query, QuerySQLTracker counter, List<Employee> originalEmployees, ServerSession session) {
    List<Employee> employees = query.getResultList();
    Employee employee = employees.get(0);
    Project project = employee.getManager().getProjects().iterator().next();
    Employee teamMember = null;
    for (Employee currentTeamMember : (Collection<Employee>) project.getTeamMembers()) {
        if (currentTeamMember.getFirstName().equals("TeamMember_NestedBatchQueryHint")) {
            teamMember = currentTeamMember;
            break;
        }
    }
    teamMember.getDealers().size();
    teamMember.getPhoneNumbers().size();
    // References have been triggered on a single object,
    // batch reading should have caused all the objects to be read,
    // therefore triggering all remaining relations should produce no sql.
    counter.getSqlStatements().clear();
    for (Employee emp : employees) {
        Employee manager = emp.getManager();
        for (Project proj : manager.getProjects()) {
            for (Employee currentTeamMember : (Collection<Employee>) proj.getTeamMembers()) {
                if (currentTeamMember != manager) {
                    currentTeamMember.getDealers().size();
                    currentTeamMember.getPhoneNumbers().size();
                }
            }
        }
    }
    String errorMsg = "";
    if (counter.getSqlStatements().size() > 0) {
        errorMsg = counter.getSqlStatements() + "\n";
    }
    if (employees.size() != originalEmployees.size()) {
        errorMsg += "employees.size() = " + employees.size() + "; originalEmployees.size() = " + originalEmployees.size() + "\n";
    } else {
        // order of read employees should be the same bacause it's ordered by last name.
        for (int i = 0; i < employees.size(); i++) {
            if (!session.compareObjects(originalEmployees.get(i), employees.get(i))) {
                errorMsg += "Original and read employee are not equal: original = " + originalEmployees.get(i).getLastName() + "; read = " + employees.get(i).getLastName() + "\n";
            }
            if (!session.compareObjects(originalEmployees.get(i).getManager(), employees.get(i).getManager())) {
                errorMsg += "Original and read employee.getManager() are not equal: original = " + originalEmployees.get(i).getManager().getLastName() + "; read = " + employees.get(i).getManager().getLastName() + "\n";
            }
            Collection<Project> projects = employees.get(i).getManager().getProjects();
            Collection<Project> originalProjects = originalEmployees.get(i).getManager().getProjects();
            for (Project originalProj : originalProjects) {
                boolean foundEqualName = false;
                for (Project proj : projects) {
                    if (originalProj.getName().equals(proj.getName())) {
                        foundEqualName = true;
                        if (!session.compareObjects(originalProj, proj)) {
                            errorMsg += "Original and read projects are not equal for name: " + originalProj.getName() + "\n";
                        }
                        break;
                    }
                }
                if (!foundEqualName) {
                    errorMsg += "No read project has name " + originalProj.getName() + "\n";
                }
            }
        }
    }
    if (errorMsg.length() > 0) {
        errorMsg = queryName + ":\n" + errorMsg;
    }
    return errorMsg;
}
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) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) CustomerCollection(org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection) Collection(java.util.Collection)

Example 20 with Project

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

the class CallbackEventJUnitTestSuite method testMergeCascadeTriggersPrePersist.

// gf 2894:  merge does not trigger prePersist callbacks
public void testMergeCascadeTriggersPrePersist() {
    clearCache();
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        // create an employee and persist it
        Employee emp = new Employee();
        emp.setFirstName("James");
        emp.setLastName("Dean");
        em.persist(emp);
        // create a new project and associate to persistent employee
        Project newProj = new Project();
        newProj.setName("Rebel Without a Cause");
        emp.addProject(newProj);
        newProj.addTeamMember(emp);
        // merge should trigger prePersist callback on project
        em.merge(emp);
        // merge returns a managed copy of an unmanaged instance
        Project managedProj = emp.getProjects().iterator().next();
        assertTrue("Cascading merge to a new object should trigger prePersist callback", managedProj.pre_persist_count == 1);
        em.merge(emp);
        // second merge should be ignored
        assertTrue("prePersist callback should only be triggered once", managedProj.pre_persist_count == 1);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : Project(org.eclipse.persistence.testing.models.jpa.advanced.Project) EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee)

Aggregations

Project (org.eclipse.persistence.testing.models.jpa.advanced.Project)65 EntityManager (jakarta.persistence.EntityManager)52 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)42 SmallProject (org.eclipse.persistence.testing.models.jpa.advanced.SmallProject)39 LargeProject (org.eclipse.persistence.testing.models.jpa.advanced.LargeProject)38 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)31 HugeProject (org.eclipse.persistence.testing.models.jpa.advanced.HugeProject)25 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)19 SpecialHugeProject (org.eclipse.persistence.testing.models.jpa.advanced.SpecialHugeProject)18 SuperLargeProject (org.eclipse.persistence.testing.models.jpa.advanced.SuperLargeProject)18 List (java.util.List)15 ArrayList (java.util.ArrayList)14 JpaCriteriaBuilder (org.eclipse.persistence.jpa.JpaCriteriaBuilder)12 Query (jakarta.persistence.Query)9 ReadAllQuery (org.eclipse.persistence.queries.ReadAllQuery)9 PhoneNumber (org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber)8 PersistenceException (jakarta.persistence.PersistenceException)6 Predicate (jakarta.persistence.criteria.Predicate)6 TypedQuery (jakarta.persistence.TypedQuery)5 HashSet (java.util.HashSet)5