Search in sources :

Example 11 with Department

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

the class EntityManagerJUnitTestSuite method testRefreshPESSIMISTIC_READLock.

public void testRefreshPESSIMISTIC_READLock() {
    // Cannot create parallel entity managers in the server.
    if (!isOnServer() && isSelectForUpateNoWaitSupported()) {
        EntityManager em = createEntityManager();
        Department dept = null;
        try {
            beginTransaction(em);
            dept = new Department();
            dept.setName("Pessimistic Department");
            em.persist(dept);
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            closeEntityManager(em);
            throw ex;
        }
        Exception pessimisticLockException = null;
        try {
            beginTransaction(em);
            dept = em.find(Department.class, dept.getId());
            em.lock(dept, LockModeType.PESSIMISTIC_READ);
            dept.setName("New Pessimistic Department");
            EntityManager em2 = createEntityManager();
            try {
                beginTransaction(em2);
                Department dept2 = em2.find(Department.class, dept.getId());
                HashMap properties = new HashMap();
                // According to the spec a 0 indicates a NOWAIT clause.
                properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
                em2.refresh(dept2, LockModeType.PESSIMISTIC_READ, properties);
            } catch (PersistenceException ex) {
                if (ex instanceof jakarta.persistence.PessimisticLockException) {
                    pessimisticLockException = ex;
                } else {
                    throw ex;
                }
            } finally {
                closeEntityManagerAndTransaction(em2);
            }
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            throw ex;
        } finally {
            closeEntityManager(em);
        }
        assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) HashMap(java.util.HashMap) PersistenceException(jakarta.persistence.PersistenceException) TestProblemException(org.eclipse.persistence.testing.framework.TestProblemException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) EclipseLinkException(org.eclipse.persistence.exceptions.EclipseLinkException) EntityExistsException(jakarta.persistence.EntityExistsException) OptimisticLockException(jakarta.persistence.OptimisticLockException) QueryException(org.eclipse.persistence.exceptions.QueryException) TransactionRequiredException(jakarta.persistence.TransactionRequiredException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) SQLException(java.sql.SQLException) RollbackException(jakarta.persistence.RollbackException) NoResultException(jakarta.persistence.NoResultException) PersistenceException(jakarta.persistence.PersistenceException) PersistenceUnitLoadingException(org.eclipse.persistence.exceptions.PersistenceUnitLoadingException)

Example 12 with Department

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

the class EntityManagerJUnitTestSuite method testPESSIMISTIC_READLock.

// This test issues a LOCK and a LOCK NOWAIT.
public void testPESSIMISTIC_READLock() {
    // Cannot create parallel entity managers in the server.
    if (!isOnServer() && isSelectForUpateNoWaitSupported()) {
        EntityManager em = createEntityManager();
        Department dept = null;
        try {
            beginTransaction(em);
            dept = new Department();
            dept.setName("Pessimistic Department");
            em.persist(dept);
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            closeEntityManager(em);
            throw ex;
        }
        Exception pessimisticLockException = null;
        try {
            beginTransaction(em);
            dept = em.find(Department.class, dept.getId());
            em.lock(dept, LockModeType.PESSIMISTIC_READ);
            dept.setName("New Pessimistic Department");
            EntityManager em2 = createEntityManager();
            try {
                beginTransaction(em2);
                Department dept2 = em2.find(Department.class, dept.getId());
                HashMap properties = new HashMap();
                // According to the spec a 0 indicates a NOWAIT clause.
                properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
                em2.lock(dept2, LockModeType.PESSIMISTIC_READ, properties);
            } catch (PersistenceException ex) {
                if (ex instanceof jakarta.persistence.PessimisticLockException) {
                    pessimisticLockException = ex;
                } else {
                    throw ex;
                }
            } finally {
                rollbackTransaction(em2);
                closeEntityManager(em2);
            }
            commitTransaction(em);
        } catch (RuntimeException ex) {
            if (isTransactionActive(em)) {
                rollbackTransaction(em);
            }
            throw ex;
        } finally {
            closeEntityManager(em);
        }
        assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Department(org.eclipse.persistence.testing.models.jpa.advanced.Department) HashMap(java.util.HashMap) PersistenceException(jakarta.persistence.PersistenceException) TestProblemException(org.eclipse.persistence.testing.framework.TestProblemException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) EclipseLinkException(org.eclipse.persistence.exceptions.EclipseLinkException) EntityExistsException(jakarta.persistence.EntityExistsException) OptimisticLockException(jakarta.persistence.OptimisticLockException) QueryException(org.eclipse.persistence.exceptions.QueryException) TransactionRequiredException(jakarta.persistence.TransactionRequiredException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) EntityNotFoundException(jakarta.persistence.EntityNotFoundException) SQLException(java.sql.SQLException) RollbackException(jakarta.persistence.RollbackException) NoResultException(jakarta.persistence.NoResultException) PersistenceException(jakarta.persistence.PersistenceException) PersistenceUnitLoadingException(org.eclipse.persistence.exceptions.PersistenceUnitLoadingException)

Example 13 with Department

use of org.eclipse.persistence.testing.models.jpa.advanced.Department 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 14 with Department

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

the class EntityManagerJUnitTestSuite method testNestedBatchQueryHint.

// Bug 320254 - Ensure we do not get an exception when using a batch hint that navigates through more than one descriptor
public void testNestedBatchQueryHint() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    Department dept = new Department();
    dept.setName("Parents");
    Employee emp = new Employee();
    emp.setFirstName("Dave");
    emp.setLastName("Daddy");
    dept.setDepartmentHead(emp);
    emp.setDepartment(dept);
    PhoneNumber pn = new PhoneNumber();
    pn.setNumber("1234567");
    pn.setAreaCode("613");
    pn.setType("Home");
    emp.addPhoneNumber(pn);
    em.persist(emp);
    em.persist(dept);
    em.persist(pn);
    em.flush();
    em.clear();
    clearCache();
    List results = em.createQuery("select d from ADV_DEPT d").setHint(QueryHints.FETCH, "d.departmentHead").setHint(QueryHints.BATCH, "d.departmentHead.phoneNumbers").getResultList();
    assertTrue("Wrong results returned.", results.size() == 1);
    dept = (Department) results.get(0);
    dept.getDepartmentHead().getPhoneNumbers().hashCode();
    rollbackTransaction(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) PhoneNumber(org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber) IndirectList(org.eclipse.persistence.indirection.IndirectList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 15 with Department

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

the class AdvancedJPAJunitTest method testBackpointerOnMerge.

/**
 * Tests that backpointers are not changed after a merge operation.
 */
public void testBackpointerOnMerge() {
    EntityManager em = createEntityManager();
    try {
        beginTransaction(em);
        // create a new department
        Department department = new Department();
        department.setName("Football");
        // persist the department
        em.persist(department);
        commitTransaction(em);
        closeEntityManager(em);
        // add equipment to the department
        em = createEntityManager();
        beginTransaction(em);
        Equipment equipment = new Equipment();
        equipment.setDescription("Shields & Dummies");
        department.addEquipment(equipment);
        em.merge(department);
        commitTransaction(em);
        closeEntityManager(em);
        assertTrue(department.getEquipment().get(0) == equipment);
        assertEquals(System.identityHashCode(department.getEquipment().get(0)), System.identityHashCode(equipment));
        assertEquals(department.getId(), equipment.getDepartment().getId());
        assertTrue("The department instance (backpointer) from equipment was modified after merge.", department == equipment.getDepartment());
        assertEquals("The department instance (backpointer) from equipment was modified after merge.", System.identityHashCode(department), System.identityHashCode(equipment.getDepartment()));
    } catch (RuntimeException e) {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEntityManager(em);
        throw e;
    }
}
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)

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