use of org.eclipse.persistence.testing.models.jpa.advanced.Project 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);
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.Project 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;
}
}
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.Project in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testDeleteEmployee_with_status_enum_collection_instantiated.
/**
* Test that deleting an employee works correctly.
* This test case was added in 8177 for 324321 and modified for 325605.
* The issue is that the status enum will be cascade deleted even if it is not
* instantiated (lazy) because the owning object does not know if the collection is empty
* without instantiating it.
* DB2 will therefore emit warning logs that are printed at FINEST in this lazy case.
* This test is a modification of testDeleteEmployee() that verifies instantiated lists are also ok
*
* 11/17/2010-2.2 Michael O'Brien
* - 325605: Filter out SQL warnings that are not SQL statements but are
* logged at a non-warning level. This affects only implementors of SessionLog that
* perform log diagnostics/tracking in addition to logging.
*/
public void testDeleteEmployee_with_status_enum_collection_instantiated() {
Employee employee = new Employee();
PhoneNumber homePhone = new PhoneNumber("home", "123", "4567");
PhoneNumber faxPhone = new PhoneNumber("fax", "456", "4567");
employee.addPhoneNumber(homePhone);
employee.addPhoneNumber(faxPhone);
employee.addResponsibility("work hard");
employee.addResponsibility("write code");
employee.addProject(new Project());
employee.setWorkWeek(new HashSet<Employee.Weekdays>());
employee.getWorkWeek().add(Employee.Weekdays.MONDAY);
employee.getWorkWeek().add(Employee.Weekdays.TUESDAY);
// set enums
// enum index is 1
employee.setStatus(Employee.EmployeeStatus.PART_TIME);
// set enum on 1 of the 2 phones, leave the other Collection of enums unset - but do a later find to instantiate the Collection
homePhone.addStatus(PhoneNumber.PhoneStatus.ASSIGNED);
QuerySQLTracker counter = new QuerySQLTracker(getServerSession());
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
closeEntityManager(em);
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
// instantiate the empty Collection of enums to verify we do not cascade delete if we "know" the Collection is empty
employee.getPhoneNumbers();
counter.getSqlStatements().clear();
em.remove(employee);
commitTransaction(em);
// We do not count any SQL warnings that may occur (DB2 may have 3) at the FINEST level
if (isWeavingEnabled() && counter.getSqlStatements().size() > 13) {
fail("Only 13 sql statements should have occured: " + counter.getSqlStatements().size());
}
beginTransaction(em);
verifyDelete(employee);
commitTransaction(em);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
if (counter != null) {
counter.remove();
}
closeEntityManager(em);
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.Project 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");
}
}
use of org.eclipse.persistence.testing.models.jpa.advanced.Project in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method internalTestUpdateAllProjectsWithNullTeamLeader.
protected void internalTestUpdateAllProjectsWithNullTeamLeader(Class<?> cls) {
if ((JUnitTestCase.getServerSession()).getPlatform().isSymfoware()) {
getServerSession().logMessage("Test testUpdateAll*ProjectsWithNullTeamLeader skipped for this platform, " + "Symfoware doesn't support UpdateAll/DeleteAll on multi-table objects (see rfe 298193).");
return;
} else if ((JUnitTestCase.getServerSession()).getPlatform().isPervasive()) {
getServerSession().logMessage("Test testUpdateAll*ProjectsWithNullTeamLeader skipped for this platform.");
return;
}
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
Employee empTemp = null;
boolean ok = false;
try {
// setup
// make sure no projects with the specified names exist
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
EntityManager em = createEntityManager();
Employee emp = null;
List employees = em.createQuery("SELECT OBJECT(e) FROM Employee e").getResultList();
if (employees.size() > 0) {
emp = (Employee) employees.get(0);
} else {
beginTransaction(em);
try {
emp = new Employee();
emp.setFirstName(name);
emp.setLastName("TeamLeader");
em.persist(emp);
commitTransaction(em);
empTemp = emp;
} finally {
closeEntityManagerAndTransaction(em);
}
}
em = createEntityManager();
beginTransaction(em);
// populate Projects
try {
createProjectsWithName(name, emp, em);
commitTransaction(em);
} finally {
closeEntityManagerAndTransaction(em);
}
// test
em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE " + className + " p set p.name = '" + newName + "' WHERE p.name = '" + name + "' AND p.teamLeader IS NULL").executeUpdate();
commitTransaction(em);
} finally {
closeEntityManagerAndTransaction(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
try {
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '" + newName + "' OR p.name = '" + name + "'").getResultList();
for (int i = 0; i < projects.size(); i++) {
Project p = (Project) projects.get(i);
String readName = p.getName();
if (cls.isInstance(p) && p.getTeamLeader() == null) {
if (!readName.equals(newName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if (readName.equals(newName)) {
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 {
// make sure no projects with the specified names exist
try {
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
if (empTemp != null) {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM Employee e WHERE e.id = '" + empTemp.getId() + "'").executeUpdate();
commitTransaction(em);
} finally {
closeEntityManagerAndTransaction(em);
}
}
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if (ok) {
throw ex;
}
}
}
}
Aggregations