use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.
the class JPAQuery method processJPQLQuery.
/**
* INTERNAL:
* Convert the JPA query into a DatabaseQuery.
*/
public DatabaseQuery processJPQLQuery(Session session) {
ClassLoader classloader = session.getDatasourcePlatform().getConversionManager().getLoader();
LockModeType lockModeEnum = null;
// Must handle errors if a JPA 2.0 option is used in JPA 1.0.
try {
lockModeEnum = LockModeType.valueOf(lockMode);
} catch (Exception ignore) {
// Ignore JPA 2.0 in JPA 1.0, reverts to no lock.
}
DatabaseQuery ejbquery = EJBQueryImpl.buildEJBQLDatabaseQuery(getName(), jpqlString, (AbstractSession) session, lockModeEnum, hints, classloader);
ejbquery.setName(getName());
return ejbquery;
}
use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.
the class EntityManagerImpl method getLockMode.
/**
* @see jakarta.persistence.EntityManager#getLockMode(java.lang.Object)
* @since Java Persistence API 2.0
*/
@Override
public LockModeType getLockMode(Object entity) {
try {
verifyOpen();
checkForTransaction(true);
UnitOfWorkImpl uowImpl = getActivePersistenceContext(checkForTransaction(false));
LockModeType lockMode = LockModeType.NONE;
if (!contains(entity, uowImpl)) {
throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cant_getLockMode_of_not_managed_object", new Object[] { entity }));
}
Boolean optimistickLock = (Boolean) uowImpl.getOptimisticReadLockObjects().get(entity);
if (optimistickLock != null) {
if (optimistickLock.equals(Boolean.FALSE)) {
lockMode = LockModeType.OPTIMISTIC;
} else {
// PESSIMISTIC_FORCE_INCREMENT
if (uowImpl.getPessimisticLockedObjects().get(entity) != null) {
lockMode = LockModeType.PESSIMISTIC_FORCE_INCREMENT;
} else {
lockMode = LockModeType.OPTIMISTIC_FORCE_INCREMENT;
}
}
} else {
// Not optimistically locked
if (uowImpl.getPessimisticLockedObjects().get(entity) != null) {
lockMode = LockModeType.PESSIMISTIC_WRITE;
}
}
return lockMode;
} catch (RuntimeException exception) {
setRollbackOnly();
throw exception;
}
}
use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.
the class PessimisticLockingExtendedScopeTestSuite method testPESSMISTIC_ES7.
// Bidirectional OneToOne Relationship with target entity has foreign key, entity does not contain the foreign key will not be locked (Scenario 3.1)
public void testPESSMISTIC_ES7() throws Exception {
if (getPlatform().isSQLServer()) {
warning("This test deadlocks on SQL Server");
return;
}
// Cannot create parallel entity managers in the server.
if (!isOnServer() && isSelectForUpateSupported()) {
EntityManager em = createEntityManager();
EntyA a = null;
EntyC c = null;
try {
beginTransaction(em);
a = new EntyA();
c = new EntyC();
em.persist(c);
a.setEntyC(c);
em.persist(a);
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);
c = em1.find(EntyC.class, c.getId());
em1.lock(c, lockMode, properties);
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
c = em2.find(EntyC.class, c.getId());
c.setEntyA(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) {
throw ex;
} finally {
if (isTransactionActive(em1)) {
rollbackTransaction(em1);
}
closeEntityManager(em1);
}
}
}
use of jakarta.persistence.LockModeType 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 jakarta.persistence.LockModeType 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