Search in sources :

Example 16 with Department

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

the class AdvancedQueryTestSuite method testMapKeyJoinFetching.

/**
 * Test join fetching of maps.
 */
public void testMapKeyJoinFetching() {
    clearCache();
    EntityManager em = createEntityManager();
    beginTransaction(em);
    // Count SQL.
    QuerySQLTracker counter = new QuerySQLTracker(getServerSession());
    try {
        Query query = em.createQuery("Select d from ADV_DEPT d");
        query.setHint(QueryHints.LEFT_FETCH, "d.equipment");
        query.setHint(QueryHints.LEFT_FETCH, "d.employees");
        query.setHint(QueryHints.LEFT_FETCH, "d.managers");
        List<Department> results = query.getResultList();
        if (isWeavingEnabled() && counter.getSqlStatements().size() > 1) {
            fail("Should have been 13 queries but was: " + counter.getSqlStatements().size());
        }
        int queries = 1;
        for (Department department : results) {
            queries = queries + department.getEquipment().size();
            department.getEmployees().size();
            department.getManagers().size();
        }
        assertTrue("No data to join.", queries > 1);
        if (isWeavingEnabled() && counter.getSqlStatements().size() > 1) {
            fail("Should have been " + 1 + " queries but was: " + counter.getSqlStatements().size());
        }
        clearCache();
        for (Department department : results) {
            verifyObject(department);
        }
    } finally {
        rollbackTransaction(em);
        closeEntityManager(em);
        if (counter != null) {
            counter.remove();
        }
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) Query(jakarta.persistence.Query) TypedQuery(jakarta.persistence.TypedQuery) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) ReadQuery(org.eclipse.persistence.queries.ReadQuery) QuerySQLTracker(org.eclipse.persistence.testing.framework.QuerySQLTracker)

Example 17 with Department

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

the class AdvancedJPAJunitTest method testJoinFetchWithRefreshOnRelatedEntity.

/**
 * Bug 415082 - JoinFetch does not refresh cache even though REFRESH hint is set to true
 * Test that a refresh is performed on a queried and related object, with fetchjoins
 */
public void testJoinFetchWithRefreshOnRelatedEntity() {
    // create test entities
    Employee emp = null;
    Department dept = null;
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        emp = new Employee("Bob", "Robertson");
        dept = new Department("Pomology");
        emp.setDepartment(dept);
        em.persist(emp);
        em.persist(dept);
        commitTransaction(em);
    } finally {
        closeEntityManager(em);
    }
    // update tables directly
    em = createEntityManager();
    try {
        beginTransaction(em);
        Session session = ((JpaEntityManager) em.getDelegate()).getActiveSession();
        if (session.getDatasourcePlatform().isSQLServer()) {
            session.executeNonSelectingSQL("UPDATE t0 SET t0.F_NAME='Joe', t0.L_NAME='Josephson' FROM CMP3_EMPLOYEE t0 WHERE t0.EMP_ID=" + emp.getId());
            session.executeNonSelectingSQL("UPDATE t1 SET t1.NAME='Xenobiology' FROM CMP3_DEPT t1 WHERE t1.ID=" + dept.getId());
        } else {
            session.executeNonSelectingSQL("UPDATE CMP3_EMPLOYEE t0 SET t0.F_NAME='Joe', t0.L_NAME='Josephson' WHERE t0.EMP_ID=" + emp.getId());
            session.executeNonSelectingSQL("UPDATE CMP3_DEPT t1 SET t1.NAME='Xenobiology' WHERE t1.ID=" + dept.getId());
        }
        commitTransaction(em);
    } finally {
        closeEntityManager(em);
    }
    // perform refreshing query
    em = createEntityManager();
    try {
        Query query = em.createQuery("select e from Employee e where e.id = :pk");
        query.setParameter("pk", emp.getId());
        query.setHint(QueryHints.REFRESH, HintValues.TRUE);
        Employee empReturned = (Employee) query.getSingleResult();
        // validate refresh
        assertNotNull("Employee should not be null", empReturned);
        Department deptReturned = empReturned.getDepartment();
        assertNotNull("Department should not be null", deptReturned);
        assertEquals("Employee should have the same id", emp.getId(), empReturned.getId());
        assertEquals("Department should have the same id", dept.getId(), deptReturned.getId());
        assertEquals("Employee's firstName should be refreshed", "Joe", empReturned.getFirstName());
        assertEquals("Employee's lastName should be refreshed", "Josephson", empReturned.getLastName());
        assertEquals("Department's name should be refreshed", "Xenobiology", deptReturned.getName());
    } finally {
        closeEntityManager(em);
    }
    // clean up
    em = createEntityManager();
    try {
        beginTransaction(em);
        em.remove(em.find(Employee.class, emp.getId()));
        em.remove(em.find(Department.class, dept.getId()));
        commitTransaction(em);
    } finally {
        closeEntityManager(em);
    }
}
Also used : Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) Query(jakarta.persistence.Query) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) DoesExistQuery(org.eclipse.persistence.queries.DoesExistQuery) TypedQuery(jakarta.persistence.TypedQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Session(org.eclipse.persistence.sessions.Session) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 18 with Department

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

the class AdvancedJPAJunitTest method testRemoveDepartmentWithPrivateOwnedEquipment.

/**
 * Tests a @PrivateOwned @OneToMany mapping.
 */
public void testRemoveDepartmentWithPrivateOwnedEquipment() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        Department department = em.find(Department.class, deptId);
        if (department == null) {
            fail("Department with id=" + deptId + ", was not found.");
        } else {
            Collection<Equipment> equipment = department.getEquipment().values();
            if (equipment.isEmpty()) {
                fail("Department with id=" + deptId + ", did not have any equipment.");
            } else {
                em.remove(department);
                commitTransaction(em);
                assertNull("Department itself was not removed.", em.find(Department.class, deptId));
                for (Equipment e : equipment) {
                    assertNull("New equipment was not deleted.", em.find(Equipment.class, e.getId()));
                }
            }
        }
    } 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)

Example 19 with Department

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

the class SimpleSerializeFetchGroupTests method copyGroupObjectGraph.

public void copyGroupObjectGraph() {
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        TypedQuery<Department> query = em.createQuery("SELECT d FROM ADV_DEPT d WHERE d.id IN (SELECT MIN(dd.id) FROM ADV_DEPT dd)", Department.class);
        Department dept = query.getSingleResult();
        CopyGroup group = new CopyGroup();
        group.addAttribute("name");
        group.addAttribute("employees", new CopyGroup());
        group.getGroup("employees").addAttribute("name");
        group.getGroup("employees").addAttribute("department", new CopyGroup());
        group.getGroup("employees").getGroup("department").addAttribute("name");
        Department deptCopy = (Department) em.unwrap(JpaEntityManager.class).copy(dept, group);
        String reportCG = group.toString();
        assertNotNull(reportCG);
    } finally {
        rollbackTransaction(em);
        closeEntityManager(em);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) CopyGroup(org.eclipse.persistence.sessions.CopyGroup)

Example 20 with Department

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

the class EntityManagerJUnitTestSuite method testMergeDetachedObject.

public void testMergeDetachedObject() {
    // Step 1 - read a department and clear the cache.
    clearCache();
    EntityManager em = createEntityManager();
    Query query = em.createNamedQuery("findAllSQLDepartments");
    Collection departments = query.getResultList();
    Department detachedDepartment;
    // and a second time with the department table empty.
    if (departments.isEmpty()) {
        beginTransaction(em);
        detachedDepartment = new Department();
        detachedDepartment.setName("Department X");
        em.persist(detachedDepartment);
        commitTransaction(em);
    } else {
        detachedDepartment = (Department) departments.iterator().next();
    }
    closeEntityManager(em);
    clearCache();
    // Step 2 - create a new em, create a new employee with the
    // detached department and then query the departments again.
    em = createEntityManager();
    beginTransaction(em);
    Employee emp = new Employee();
    emp.setFirstName("Crazy");
    emp.setLastName("Kid");
    emp.setId(41);
    emp.setDepartment(detachedDepartment);
    em.persist(emp);
    commitTransaction(em);
    try {
        em.createNamedQuery("findAllSQLDepartments").getResultList();
    } catch (NullPointerException e) {
        assertTrue("The detached department caused a null pointer on the query execution.", false);
    }
    closeEntityManager(em);
}
Also used : 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) 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) CustomerCollection(org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection) Collection(java.util.Collection)

Aggregations

Department (org.eclipse.persistence.testing.models.jpa.advanced.Department)32 EntityManager (jakarta.persistence.EntityManager)31 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)23 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)10 Equipment (org.eclipse.persistence.testing.models.jpa.advanced.Equipment)10 UnitOfWorkImpl (org.eclipse.persistence.internal.sessions.UnitOfWorkImpl)8 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)6 PersistenceException (jakarta.persistence.PersistenceException)6 Address (org.eclipse.persistence.testing.models.jpa.advanced.Address)6 EntityExistsException (jakarta.persistence.EntityExistsException)5 EntityNotFoundException (jakarta.persistence.EntityNotFoundException)5 NoResultException (jakarta.persistence.NoResultException)5 OptimisticLockException (jakarta.persistence.OptimisticLockException)5 Query (jakarta.persistence.Query)5 RollbackException (jakarta.persistence.RollbackException)5 TransactionRequiredException (jakarta.persistence.TransactionRequiredException)5 SQLException (java.sql.SQLException)5 HashMap (java.util.HashMap)5 EclipseLinkException (org.eclipse.persistence.exceptions.EclipseLinkException)5 IntegrityException (org.eclipse.persistence.exceptions.IntegrityException)5