use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.
the class QueryCastTestSuite method testDowncastManyToManyQueryKey.
public void testDowncastManyToManyQueryKey() {
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();
Query query = em.createQuery("Select e from Employee e join treat(e.projects as LargeProject) p where p.budget > 100");
List resultList = query.getResultList();
assertTrue("Incorrect results returned", resultList.size() == 1);
} finally {
if (this.isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.
the class PessimisticLockingExtendedScopeTestSuite method testPESSMISTIC_ES9.
// Bidirectional ManyToMany Relationship, in which entity does not contain the foreign key will not be locked by default (Scenario 3.3)
public void testPESSMISTIC_ES9() throws Exception {
if (getPlatform().isSQLServer()) {
warning("This test deadlocks on SQL Server");
return;
}
if ((JUnitTestCase.getServerSession()).getPlatform().isHANA()) {
// feature is under development (see bug 384129), but test should be skipped for the time being
return;
}
// Cannot create parallel entity managers in the server.
if (!isOnServer() && isSelectForUpateSupported()) {
EntityManager em = createEntityManager();
Employee emp = null;
try {
beginTransaction(em);
emp = new Employee();
SmallProject smallProject = new SmallProject();
smallProject.setName("New High School Set Up");
emp.addProject(smallProject);
LargeProject largeProject = new LargeProject();
largeProject.setName("Downtown Light Rail");
largeProject.setBudget(5000);
emp.addProject(largeProject);
em.persist(emp);
commitTransaction(em);
} catch (RuntimeException ex) {
throw ex;
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
Exception lockTimeOutException = null;
LockModeType lockMode = LockModeType.PESSIMISTIC_WRITE;
Map<String, Object> properties = new HashMap();
properties.put(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.NORMAL);
EntityManager em1 = createEntityManager();
try {
beginTransaction(em1);
emp = em1.find(Employee.class, emp.getId());
em1.lock(emp, lockMode, properties);
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
emp = em1.find(Employee.class, emp.getId());
emp.setProjects(null);
commitTransaction(em2);
} catch (jakarta.persistence.RollbackException ex) {
fail("it should not throw the exception!!!");
} finally {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
closeEntityManager(em2);
}
} catch (Exception ex) {
fail("it should not throw the exception!!!");
throw ex;
} finally {
if (isTransactionActive(em1)) {
rollbackTransaction(em1);
}
closeEntityManager(em1);
}
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.
the class CriteriaQueryCastTestSuite method testCastInSubselect.
public void testCastInSubselect() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
LargeProject proj = new LargeProject();
proj.setBudget(1000);
proj.setName("test1");
em.persist(proj);
LargeProject lp = new LargeProject();
lp.setBudget(100);
lp.setName("sp1");
em.persist(lp);
Employee emp = new Employee();
emp.setFirstName("Reggie");
emp.setLastName("Josephson");
emp.addProject(proj);
proj.addTeamMember(emp);
emp.addProject(lp);
lp.addTeamMember(emp);
emp.setSalary(10000);
em.persist(emp);
emp = new Employee();
emp.setFirstName("Ron");
emp.setLastName("Josephson");
emp.addProject(lp);
lp.addTeamMember(emp);
em.persist(emp);
emp.setSalary(100);
em.flush();
clearCache();
em.clear();
// Query query = em.createQuery("select e from Employee e where e.salary > (Select max(l.budget) from Employee emp join treat(emp.projects as LargeProject) l)");
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> root = cq.from(Employee.class);
Subquery<Number> sq = cq.subquery(Number.class);
Root<Employee> sRoot = sq.from(Employee.class);
Join<Object, LargeProject> l = qb.treat(root.join("projects"), LargeProject.class);
sq.select(qb.max(l.get("budget")));
cq.where(qb.gt(root.<Number>get("salary"), sq));
List<Employee> resultList = em.createQuery(cq).getResultList();
assertTrue("Incorrect result size returned", resultList.size() == 1);
} finally {
if (this.isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method internalTestChangeRecordKeepOldValue.
public void internalTestChangeRecordKeepOldValue(boolean addSecondStep) {
if (isOnServer()) {
// the test relies upon keeping attached objects between transactions.
return;
}
ServerSession ss = getServerSession();
ChangeRecordKeepOldValueListener listener = new ChangeRecordKeepOldValueListener();
ss.getEventManager().addListener(listener);
EntityManager em = createEntityManager();
try {
// setup
// create original object and referenced objects
Employee emp = new Employee();
emp.setFirstName("TestChangeRecordKeepOldValue");
emp.setLastName("Manager_OriginalName");
emp.setMale();
emp.setSalary(35000);
emp.setPeriod(new EmploymentPeriod(Helper.dateFromYearMonthDate(1993, 0, 1), Helper.dateFromYearMonthDate(1996, 11, 31)));
emp.setFormerEmployment(new FormerEmployment("Original", new EmploymentPeriod(Helper.dateFromYearMonthDate(1990, 0, 1), Helper.dateFromYearMonthDate(1993, 11, 31))));
Address address = new Address();
address.setCountry("Original");
address.setProvince("Original");
address.setCity("Original");
address.setStreet("Original");
address.setPostalCode("Original");
emp.setAddress(address);
Department dep = new Department();
dep.setName("Original");
emp.setDepartment(dep);
emp.addResponsibility("Original_1");
emp.addResponsibility("Original_2");
PhoneNumber phone1 = new PhoneNumber("Original_1", "111", "1111111");
emp.addPhoneNumber(phone1);
PhoneNumber phone2 = new PhoneNumber("Original_2", "222", "2222222");
emp.addPhoneNumber(phone2);
emp.setNormalHours(new Time[] { Helper.timeFromHourMinuteSecond(9, 0, 0), Helper.timeFromHourMinuteSecond(17, 0, 0) });
Employee emp1 = new Employee();
emp1.setFirstName("TestChangeRecordKeepOldValue");
emp1.setLastName("Original_1");
emp.addManagedEmployee(emp1);
Employee emp2 = new Employee();
emp2.setFirstName("TestChangeRecordKeepOldValue");
emp2.setLastName("Original_2");
emp.addManagedEmployee(emp2);
Project proj1 = new SmallProject();
proj1.setName("Original_1");
emp.addProject(proj1);
Project proj2 = new LargeProject();
proj2.setName("Original_2");
emp.addProject(proj2);
Project proj3 = new LargeProject();
proj3.setName("Original_3");
proj3.setTeamLeader(emp);
emp1.addProject(proj3);
emp2.addProject(proj3);
// persist original object and all referenced objects
beginTransaction(em);
Equipment equipment1 = new Equipment();
equipment1.setDescription("Original_1");
// persist is not cascaded for department.equipment - have to explicitly persist it.
em.persist(equipment1);
dep.addEquipment(equipment1);
Equipment equipment2 = new Equipment();
equipment2.setDescription("Original_2");
// persist is not cascaded for department.equipment - have to explicitly persist it.
// moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
// should be persisted before been added to dep.
em.persist(equipment2);
dep.addEquipment(equipment2);
// persist is not cascaded for employee.department - have to explicitly persist it.
// moreover, equipment.id is used as a key in dep.equipment Map, therefore equipmet
// should be persisted before been added to dep.
em.persist(dep);
em.persist(emp);
commitTransaction(em);
// backup original object and all referenced objects
CopyGroup copyGroupBackup = new CopyGroup();
copyGroupBackup.cascadeAllParts();
ss.copy(emp, copyGroupBackup);
// emp references (directly or through other objects) all the created objects, therefore all of them are copied.
Map backupMap = copyGroupBackup.getCopies();
// verify that backup objects are identical to originals
Iterator<Map.Entry> it = backupMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
Object original = entry.getKey();
ClassDescriptor descriptor = ss.getDescriptor(original);
if (!descriptor.isAggregateDescriptor()) {
Object backup = entry.getValue();
if (original == backup) {
fail("Test problem: backup failed: original == backup: " + original);
}
if (!ss.compareObjects(original, backup)) {
fail("Test problem: backup failed: compareObjects(original, backup) == false: " + original + "; " + backup);
}
}
}
// change original object
beginTransaction(em);
// DirectToField
emp.setLastName("Manager_NewName");
// DirectToField
emp.setSalary(100);
// Aggregate
emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2000, 0, 1));
emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2002, 0, 1));
// Aggregate
// emp.setFormerEmployment(new FormerEmployment("New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1989, 0, 1), Helper.dateFromYearMonthDate(1992, 11, 31))));
emp.getFormerEmployment().setFormerCompany("New");
emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1989, 0, 1));
emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1992, 11, 31));
// Transformation
emp.setStartTime(Helper.timeFromHourMinuteSecond(10, 0, 0));
// DirectCollection
emp.removeResponsibility("Original_1");
emp.addResponsibility("New_1");
// Private Collection 1 to many
PhoneNumber phone1New = new PhoneNumber("New_1", "111", "1111111");
emp.addPhoneNumber(phone1New);
emp.removePhoneNumber(phone1);
// Collection 1 to many
emp.removeManagedEmployee(emp1);
emp1.setManager(null);
em.remove(emp1);
Employee emp1New = new Employee();
emp1New.setFirstName("TestChangeRecordKeepOldValue");
emp1New.setLastName("New_1");
emp1New.addProject(proj3);
emp.addManagedEmployee(emp1New);
// Collection many to many
emp.removeProject(proj1);
em.remove(proj1);
Project proj1New = new LargeProject();
proj1New.setName("New_1");
emp.addProject(proj1New);
// ObjectReference
proj3.setTeamLeader(null);
// ObjectReference
Address addressNew = new Address();
addressNew.setCountry("New");
addressNew.setProvince("New");
addressNew.setCity("New");
addressNew.setStreet("New");
addressNew.setPostalCode("New");
emp.setAddress(addressNew);
em.remove(address);
// Map 1 to many
dep.getEquipment().remove(equipment1.getId());
Equipment equipment1New = new Equipment();
equipment1New.setDescription("New_1");
em.persist(equipment1New);
dep.addEquipment(equipment1New);
// additional change typically overrides existing aggregate or collection with the new one, then alters aggregate or adds to collection.
if (addSecondStep) {
// Aggregate
emp.setPeriod(new EmploymentPeriod());
emp.getPeriod().setStartDate(Helper.dateFromYearMonthDate(2001, 0, 1));
emp.getPeriod().setEndDate(Helper.dateFromYearMonthDate(2003, 0, 1));
// Aggregate
emp.setFormerEmployment(new FormerEmployment("New_New", new EmploymentPeriod(Helper.dateFromYearMonthDate(1988, 0, 1), Helper.dateFromYearMonthDate(1991, 11, 31))));
emp.getFormerEmployment().setPeriod(new EmploymentPeriod());
emp.getFormerEmployment().getPeriod().setStartDate(Helper.dateFromYearMonthDate(1987, 0, 1));
emp.getFormerEmployment().getPeriod().setEndDate(Helper.dateFromYearMonthDate(1990, 0, 1));
// Transformation
emp.setEndTime(Helper.timeFromHourMinuteSecond(18, 0, 0));
// DirectCollection
emp.setResponsibilities(new ArrayList());
emp.addResponsibility("New_New_1");
// Private Collection 1 to many
emp.setPhoneNumbers(new HashSet());
PhoneNumber phone1NewNew = new PhoneNumber("New_New_1", "111", "1111111");
emp.addPhoneNumber(phone1NewNew);
// Collection 1 to many
emp1New.setManager(null);
emp2.setManager(null);
emp.setManagedEmployees(new Vector());
Employee emp1NewNew = new Employee();
emp1NewNew.setFirstName("TestChangeRecordKeepOldValue");
emp1NewNew.setLastName("New_New_1");
emp1NewNew.addProject(proj3);
emp.addManagedEmployee(emp1NewNew);
em.remove(emp1New);
em.remove(emp2);
// Collection many to many
emp.setProjects(new ArrayList());
Project proj1NewNew = new LargeProject();
proj1NewNew.setName("New_New_1");
emp.addProject(proj1NewNew);
em.remove(proj1New);
em.remove(proj2);
// ObjectReference
Address addressNewNew = new Address();
addressNewNew.setCountry("New_New");
addressNewNew.setProvince("New_New");
addressNewNew.setCity("New_New");
addressNewNew.setStreet("New_New");
addressNewNew.setPostalCode("New_New");
emp.setAddress(addressNewNew);
em.remove(addressNew);
// Map 1 to many
// We are about to override equipment map.
// It's a private OneToMany mapping so normally all the
// members would be removed automatically.
// However in theis case we have explicitly persisted the the new member added in thhe current transaction
// (because Equipment's id is used as its key in the Department.equipment Map)
// therefore we have to explicitly em.remove it.
em.remove(equipment1New);
dep.setEquipment(new HashMap());
Equipment equipment1NewNew = new Equipment();
equipment1NewNew.setDescription("New_New_1");
em.persist(equipment1NewNew);
dep.addEquipment(equipment1NewNew);
}
commitTransaction(em);
// backup updated objects
CopyGroup copyGroupUpdated = new CopyGroup();
copyGroupUpdated.cascadeAllParts();
ss.copy(emp, copyGroupUpdated);
// copies of the updated objects will be altered to contain old values.
// if altering the test, make sure that emp still references (directly or through other objects) all the updated objects, so that all of them are copied.
Map oldValueMap = copyGroupUpdated.getCopies();
// using ChangeRecords bring back the original state of the object
Iterator<Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet>> itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
while (itChangeSets.hasNext()) {
Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
Object object = entry.getKey();
ClassDescriptor descriptor = ss.getDescriptor(object);
if (!descriptor.isAggregateDescriptor()) {
org.eclipse.persistence.internal.sessions.ObjectChangeSet changeSet = entry.getValue();
if (!changeSet.shouldBeDeleted() && !changeSet.isNew()) {
List<ChangeRecord> changes = changeSet.getChanges();
if (changes != null && !changes.isEmpty()) {
Object oldValueObject = oldValueMap.get(object);
for (ChangeRecord changeRecord : changeSet.getChanges()) {
Object oldValue = changeRecord.getOldValue();
DatabaseMapping mapping = ((org.eclipse.persistence.internal.sessions.ChangeRecord) changeRecord).getMapping();
mapping.setRealAttributeValueInObject(oldValueObject, oldValue);
}
}
}
}
}
String errorMsgOldValues = "";
// now compare oldValue objects with corresponding backup objects
itChangeSets = ((org.eclipse.persistence.internal.sessions.UnitOfWorkChangeSet) listener.uowChangeSet).getCloneToObjectChangeSet().entrySet().iterator();
while (itChangeSets.hasNext()) {
Map.Entry<Object, org.eclipse.persistence.internal.sessions.ObjectChangeSet> entry = itChangeSets.next();
Object object = entry.getKey();
ClassDescriptor descriptor = ss.getDescriptor(object);
if (!descriptor.isAggregateDescriptor()) {
ObjectChangeSet changeSet = entry.getValue();
if (!changeSet.shouldBeDeleted() && !changeSet.isNew()) {
List<ChangeRecord> changes = changeSet.getChanges();
if (changes != null && !changes.isEmpty()) {
Object oldValueObject = oldValueMap.get(object);
Object backupObject = backupMap.get(object);
// compare oldValue with backup object
if (!ss.compareObjects(oldValueObject, backupObject)) {
errorMsgOldValues += '\t' + object.toString() + '\n';
}
}
}
}
}
// set of attached to em objects
Set updatedObjects = new HashSet();
for (Object object : oldValueMap.keySet()) {
ClassDescriptor descriptor = ss.getDescriptor(object);
if (!descriptor.isAggregateDescriptor()) {
updatedObjects.add(object);
}
}
// verify that the objects were correctly written to the db
String errorMsgDb = "";
clearCache();
Map updatedToReadBack = new HashMap();
EntityManager em2 = createEntityManager();
beginTransaction(em2);
UnitOfWork uow2 = ((EntityManagerImpl) em2.getDelegate()).getActivePersistenceContext(null);
// before comparison clear all read-only mappings that we didn't set in the attached to em objects.
for (Object object : updatedObjects) {
Object readBack = uow2.readObject(object);
if (readBack instanceof Project) {
((Project) readBack).getTeamMembers().clear();
} else if (readBack instanceof Address) {
((Address) readBack).getEmployees().clear();
} else if (readBack instanceof PhoneNumber) {
((PhoneNumber) readBack).setId(null);
} else if (readBack instanceof Department) {
((Department) readBack).getEmployees().clear();
}
updatedToReadBack.put(object, readBack);
}
// now compare object attached to em with the object read from the db
for (Object entryObject : updatedToReadBack.entrySet()) {
Map.Entry entry = (Map.Entry) entryObject;
Object object = entry.getKey();
Object readBack = entry.getValue();
if (!ss.compareObjects(object, readBack)) {
errorMsgDb += '\t' + object.toString() + '\n';
}
}
rollbackTransaction(em2);
// clean up
beginTransaction(em);
Set objectsToRemove = new HashSet();
// remove all dependencies and add cache objects to be directly removed.
for (Object object : updatedObjects) {
if (object instanceof Employee) {
((Employee) object).getManagedEmployees().clear();
((Employee) object).setManager(null);
((Employee) object).setAddress((Address) null);
((Employee) object).getProjects().clear();
((Employee) object).setDepartment(null);
objectsToRemove.add(object);
} else if (object instanceof Project) {
((Project) object).setTeamLeader(null);
objectsToRemove.add(object);
} else if (object instanceof Address || object instanceof Department) {
objectsToRemove.add(object);
}
}
// remove objects that should be removed directly.
for (Object object : objectsToRemove) {
em.remove(object);
}
commitTransaction(em);
String errorMsg = "";
if (errorMsgOldValues.length() > 0) {
errorMsgOldValues = "Some old values and back up objects are not equal:\n" + errorMsgOldValues;
errorMsg += errorMsgOldValues;
}
if (errorMsgDb.length() > 0) {
errorMsgDb = "\nSome values were incorrectly written into the db:\n" + errorMsgDb;
errorMsg += errorMsgDb;
}
if (errorMsg.length() > 0) {
fail(errorMsg);
}
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
ss.getEventManager().removeListener(listener);
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.LargeProject in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testPESSIMISTIC_ExtendedScope.
public void testPESSIMISTIC_ExtendedScope() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server. Uses FOR UPDATE clause which SQLServer doesn't support.
if (isOnServer() || !isSelectForUpateSupported() || !isPessimisticWriteLockSupported()) {
return;
}
if ((JUnitTestCase.getServerSession()).getPlatform().isHANA()) {
// feature is under development (see bug 384129), but test should be skipped for the time being
return;
}
ServerSession ss = ((JpaEntityManagerFactory) getEntityManagerFactory()).getServerSession();
// If FOR UPDATE NOWAIT is not supported then FOR UPDATE is used - and that could lock the test (em2) for a long time (depending on db setting).
boolean shouldSpawnThread = !isSelectForUpateNoWaitSupported();
// To avoid that a separate thread is spawned that - after waiting the specified time -
// completes the locking transaction (em1) and therefore clears the way to em2 go ahead.
long timeToWait = 1000;
String errorMsg = "";
LockModeType lockMode = LockModeType.PESSIMISTIC_WRITE;
// create Employee with Projects and Responsibilities
Employee emp = new Employee();
emp.setFirstName("PESSIMISTIC");
emp.setLastName("ExtendedScope");
emp.addResponsibility("0");
emp.addResponsibility("1");
SmallProject smallProject = new SmallProject();
smallProject.setName("SmallExtendedScope");
emp.addProject(smallProject);
LargeProject largeProject = new LargeProject();
largeProject.setName("LargeExtendedScope");
largeProject.setBudget(5000);
emp.addProject(largeProject);
// persist
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// cache ids
int id = emp.getId();
int smallProjId = smallProject.getId();
clearCache();
// properties to be passed to find, lock, refresh methods
Map<String, Object> properties = new HashMap();
properties.put(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
String forUpdateClause = session.getPlatform().getSelectForUpdateString();
if (isSelectForUpateNoWaitSupported()) {
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
forUpdateClause = session.getPlatform().getSelectForUpdateNoWaitString();
}
String lockingClauseAfterWhereClause = "";
String lockingClauseBeforeWhereClause = "";
if (session.getPlatform().shouldPrintLockingClauseAfterWhereClause()) {
lockingClauseAfterWhereClause = forUpdateClause;
} else {
lockingClauseBeforeWhereClause = forUpdateClause;
}
// indicates whether the object to be locked is already in cache.
boolean[] isObjectCached = { false, true };
// indicates which method on the first entity manager is used to lock the object.
String[] testModeArray1 = { "query", "find", "lock", "refresh" };
// indicates which method on the second entity manager is used to test the lock.
String[] testModeArray2 = { "query", "find", "update_name", "update_salary", "remove_project", "remove_respons", "update_project", "update_respons", "lock", "refresh" };
if (usesSOP()) {
// if SOP is used there is no expected exceptions for remove_respons and update_respons because responsibilities read from sopObject, not from db row directly.
// Therefore exclude remove_respons and update_respons.
testModeArray2 = new String[] { "query", "find", "update_name", "update_salary", "remove_project", "update_project", "lock", "refresh" };
}
// testMode1 loop
for (int i = 0; i < testModeArray1.length; i++) {
String testMode1 = testModeArray1[i];
// isObjectCached loop
for (int k = 0; k < isObjectCached.length; k++) {
boolean isObjCached = isObjectCached[k];
// testMode2 loop
for (int j = 0; j < testModeArray2.length; j++) {
String testMode2 = testModeArray2[j];
boolean isExceptionExpected = !testMode2.equals("update_project");
// lock emp using em1
EntityManager em1 = createEntityManager();
// bring object into cache if required
if (isObjCached) {
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: bring object into cache", null, null, false);
em1.find(Employee.class, id);
}
Employee emp1;
try {
beginTransaction(em1);
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode1 = " + testMode1, null, null, false);
if (testMode1.equals("query")) {
Query query1 = em1.createQuery("SELECT emp FROM Employee emp WHERE emp.id = " + id).setLockMode(lockMode).setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
if (isSelectForUpateNoWaitSupported()) {
query1.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
}
emp1 = (Employee) query1.getSingleResult();
} else if (testMode1.equals("find")) {
emp1 = em1.find(Employee.class, id, lockMode, properties);
} else {
emp1 = em1.find(Employee.class, id);
if (testMode1.equals("lock")) {
em1.lock(emp1, lockMode, properties);
} else if (testMode1.equals("refresh")) {
em1.refresh(emp1, lockMode, properties);
} else {
fail("Unknown testMode1 = " + testMode1);
}
}
TransactionKiller transactionKiller = null;
// try to update emp using em2
EntityManager em2 = createEntityManager();
Employee emp2;
try {
beginTransaction(em2);
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode2 = " + testMode2, null, null, false);
if (shouldSpawnThread) {
// after waiting TransactionKiller rollback em1 transaction unlocking way for em2 to proceed.
// the test assumes that em2 waiting for timeToWait means em2 waiting on the lock acquired by em1.
transactionKiller = new TransactionKiller(em1, timeToWait);
transactionKiller.start();
}
if (testMode2.equals("query")) {
Query query2 = em2.createQuery("SELECT emp FROM Employee emp WHERE emp.id = " + id).setLockMode(lockMode).setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
if (isSelectForUpateNoWaitSupported()) {
query2.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
}
emp2 = (Employee) query2.getSingleResult();
} else if (testMode2.equals("find")) {
emp2 = em2.find(Employee.class, id, lockMode, properties);
} else if (testMode2.equals("update_name")) {
em2.createNativeQuery("SELECT L_NAME FROM CMP3_EMPLOYEE" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_EMPLOYEE SET L_NAME = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
} else if (testMode2.equals("update_salary")) {
em2.createNativeQuery("SELECT SALARY FROM CMP3_SALARY" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_SALARY SET SALARY = 1000 WHERE EMP_ID = "+id).executeUpdate();
} else if (testMode2.equals("remove_project")) {
em2.createNativeQuery("SELECT PROJECTS_PROJ_ID FROM CMP3_EMP_PROJ" + lockingClauseBeforeWhereClause + " WHERE EMPLOYEES_EMP_ID = " + id + lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("DELETE FROM CMP3_EMP_PROJ WHERE EMPLOYEES_EMP_ID = "+id).executeUpdate();
} else if (testMode2.equals("remove_respons")) {
em2.createNativeQuery("SELECT EMP_ID FROM CMP3_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("DELETE FROM CMP3_RESPONS WHERE EMP_ID = "+id).executeUpdate();
} else if (testMode2.equals("update_project")) {
em2.createNativeQuery("SELECT PROJ_NAME FROM CMP3_PROJECT" + lockingClauseBeforeWhereClause + " WHERE PROJ_ID = " + smallProjId + lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_PROJECT SET PROJ_NAME = 'NEW' WHERE PROJ_ID = "+smallProjId).executeUpdate();
} else if (testMode2.equals("update_respons")) {
em2.createNativeQuery("SELECT DESCRIPTION FROM CMP3_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("UPDATE CMP3_RESPONS SET DESCRIPTION = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
} else {
emp2 = em2.find(Employee.class, id);
if (testMode2.equals("lock")) {
em2.lock(emp2, lockMode, properties);
} else if (testMode2.equals("refresh")) {
em2.refresh(emp2, lockMode, properties);
} else {
fail("Unknown testMode2 = " + testMode2);
}
}
// commitTransaction(em2);
boolean hasKilledTransaction = false;
if (transactionKiller != null) {
transactionKiller.shouldKillTransaction = false;
try {
transactionKiller.join();
} catch (InterruptedException intEx) {
// Ignore
}
hasKilledTransaction = transactionKiller.hasKilledTransaction;
}
// transaction killed by TransactionKiller is treated as PessimisticLockException
if (isExceptionExpected && !hasKilledTransaction) {
String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Exception was expected.";
ss.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, null, null, false);
errorMsg += '\n' + localErrorMsg;
}
} catch (Exception ex) {
if (transactionKiller != null) {
transactionKiller.shouldKillTransaction = false;
try {
transactionKiller.join();
} catch (InterruptedException intEx) {
// Ignore
}
}
if (!isExceptionExpected) {
String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Unexpected exception: " + ex.getMessage();
ss.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, null, null, false);
errorMsg += '\n' + localErrorMsg;
}
} finally {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
closeEntityManager(em2);
}
// commitTransaction(em1);
} finally {
if (isTransactionActive(em1)) {
rollbackTransaction(em1);
}
closeEntityManager(em1);
}
clearCache();
}
// testModel2 loop
}
// isObjectCached loop
}
// testMode1 loop
// clean up
em = createEntityManager();
emp = em.find(Employee.class, id);
try {
beginTransaction(em);
Iterator<Project> it = emp.getProjects().iterator();
while (it.hasNext()) {
Project project = it.next();
it.remove();
em.remove(project);
}
em.remove(emp);
commitTransaction(em);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
if (errorMsg.length() > 0) {
fail(errorMsg);
}
}
Aggregations