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 hibernate-orm by hibernate.
the class QueryHintDefinition method determineLockOptions.
public LockOptions determineLockOptions(NamedQuery namedQueryAnnotation) {
final LockModeType lockModeType = namedQueryAnnotation.lockMode();
final Integer lockTimeoutHint = specLockTimeout();
final Boolean followOnLocking = getBooleanWrapper(HibernateHints.HINT_FOLLOW_ON_LOCKING);
return determineLockOptions(lockModeType, lockTimeoutHint, followOnLocking);
}
use of jakarta.persistence.LockModeType in project hibernate-orm by hibernate.
the class NamedQueryHelper method determineLockOptions.
private static LockOptions determineLockOptions(Map<String, Object> hints, SessionFactoryImplementor sessionFactory) {
final Object lockModeSetting = hints.get(HINT_NATIVE_LOCK_MODE);
final LockMode lockMode;
if (lockModeSetting == null) {
lockMode = LockMode.NONE;
} else if (lockModeSetting instanceof LockMode) {
lockMode = (LockMode) lockModeSetting;
} else if (lockModeSetting instanceof LockModeType) {
lockMode = LockModeTypeHelper.getLockMode((LockModeType) lockModeSetting);
} else {
lockMode = LockMode.fromExternalForm(lockModeSetting.toString());
}
if (lockMode == LockMode.NONE) {
return LockOptions.NONE;
} else {
return new LockOptions(lockMode);
}
}
use of jakarta.persistence.LockModeType in project eclipselink by eclipse-ee4j.
the class EntityManagerJUnitTestSuite method testPESSIMISTIC_ExtendedScope.
public void testPESSIMISTIC_ExtendedScope() {
// Cannot create parallel entity managers in the server. Uses FOR UPDATE clause which SQLServer doesn't support.
if (isOnServer() || !isSelectForUpateSupported() || !isPessimisticWriteLockSupported()) {
return;
}
// 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);
DatabasePlatform platform = (DatabasePlatform) getPlatform();
String forUpdateClause = platform.getSelectForUpdateString();
if (isSelectForUpateNoWaitSupported()) {
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
forUpdateClause = platform.getSelectForUpdateNoWaitString();
}
String lockingClauseAfterWhereClause = "";
String lockingClauseBeforeWhereClause = "";
if (platform.shouldPrintLockingClauseAfterWhereClause()) {
lockingClauseAfterWhereClause = forUpdateClause;
} else {
lockingClauseBeforeWhereClause = forUpdateClause;
}
SessionBroker broker = getSessionBroker();
// 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" };
// 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) {
broker.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: bring object into cache", null, null, false);
em1.find(Employee.class, id);
}
Employee emp1;
try {
beginTransaction(em1);
broker.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);
broker.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 MBR2_EMPLOYEE" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(2)).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 MBR2_SALARY" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(2)).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 MBR3_EMP_PROJ" + lockingClauseBeforeWhereClause + " WHERE EMPLOYEES_EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(3)).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 MBR1_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(1)).getResultList();
// em2.createNativeQuery("DELETE FROM CMP3_RESPONS WHERE EMP_ID = "+id).executeUpdate();
} else if (testMode2.equals("update_project")) {
em2.createNativeQuery("SELECT PROJ_NAME FROM MBR3_PROJECT" + lockingClauseBeforeWhereClause + " WHERE PROJ_ID = " + smallProjId + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(3)).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 MBR1_RESPONS" + lockingClauseBeforeWhereClause + " WHERE EMP_ID = " + id + lockingClauseAfterWhereClause).setHint(QueryHints.COMPOSITE_UNIT_MEMBER, getCompositeMemberPuName(1)).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.";
broker.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();
broker.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