javax.persistence.LockModeType Java Examples
The following examples show how to use
javax.persistence.LockModeType.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LockModeConverter.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Convert from the Hibernate specific LockMode to the JPA defined LockModeType. * * @param lockMode The Hibernate LockMode. * * @return The JPA LockModeType */ public static LockModeType convertToLockModeType(LockMode lockMode) { if ( lockMode == LockMode.NONE ) { return LockModeType.NONE; } else if ( lockMode == LockMode.OPTIMISTIC || lockMode == LockMode.READ ) { return LockModeType.OPTIMISTIC; } else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT || lockMode == LockMode.WRITE ) { return LockModeType.OPTIMISTIC_FORCE_INCREMENT; } else if ( lockMode == LockMode.PESSIMISTIC_READ ) { return LockModeType.PESSIMISTIC_READ; } else if ( lockMode == LockMode.PESSIMISTIC_WRITE || lockMode == LockMode.UPGRADE || lockMode == LockMode.UPGRADE_NOWAIT || lockMode == LockMode.UPGRADE_SKIPLOCKED) { return LockModeType.PESSIMISTIC_WRITE; } else if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT || lockMode == LockMode.FORCE ) { return LockModeType.PESSIMISTIC_FORCE_INCREMENT; } throw new AssertionFailure( "unhandled lock mode " + lockMode ); }
Example #2
Source File: OptimisticLockingIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test(expected = OptimisticLockException.class) public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { EntityManager em = getEntityManagerWithOpenTransaction(); OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); em.lock(student, LockModeType.OPTIMISTIC); EntityManager em2 = getEntityManagerWithOpenTransaction(); OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); student2.setName("RICHARD"); em2.persist(student2); em2.getTransaction() .commit(); em2.close(); student.setName("JOHN"); em.persist(student); em.getTransaction() .commit(); em.close(); }
Example #3
Source File: JpaLockingStrategy.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override @Transactional(readOnly = false) public void release() { final Lock lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); if (lock == null) { return; } // Only the current owner can release the lock final String owner = lock.getUniqueId(); if (uniqueId.equals(owner)) { lock.setUniqueId(null); lock.setExpirationDate(null); logger.debug("Releasing {} lock held by {}.", applicationId, uniqueId); entityManager.persist(lock); } else { throw new IllegalStateException("Cannot release lock owned by " + owner); } }
Example #4
Source File: JpaTicketRegistry.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
private void deleteTicketAndChildren(final Ticket ticket) { final List<TicketGrantingTicketImpl> ticketGrantingTicketImpls = entityManager .createQuery("select t from TicketGrantingTicketImpl t where t.ticketGrantingTicket.id = :id", TicketGrantingTicketImpl.class) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .setParameter("id", ticket.getId()) .getResultList(); final List<ServiceTicketImpl> serviceTicketImpls = entityManager .createQuery("select s from ServiceTicketImpl s where s.ticketGrantingTicket.id = :id", ServiceTicketImpl.class) .setParameter("id", ticket.getId()) .getResultList(); for (final ServiceTicketImpl s : serviceTicketImpls) { removeTicket(s); } for (final TicketGrantingTicketImpl t : ticketGrantingTicketImpls) { deleteTicketAndChildren(t); } removeTicket(ticket); }
Example #5
Source File: PrimaryStorageCapacityUpdater.java From zstack with Apache License 2.0 | 6 votes |
private boolean lockCapacity() { if (primaryStorageUuid != null) { capacityVO = dbf.getEntityManager().find(PrimaryStorageCapacityVO.class, primaryStorageUuid, LockModeType.PESSIMISTIC_WRITE); } else if (query != null) { query.setLockMode(LockModeType.PESSIMISTIC_WRITE); List<PrimaryStorageCapacityVO> caps = query.getResultList(); capacityVO = caps.isEmpty() ? null : caps.get(0); } if (capacityVO != null) { totalForLog = capacityVO.getTotalCapacity(); availForLog = capacityVO.getAvailableCapacity(); totalPhysicalForLog = capacityVO.getTotalPhysicalCapacity(); availPhysicalForLog = capacityVO.getAvailablePhysicalCapacity(); originalCopy = new PrimaryStorageCapacityVO(); originalCopy.setAvailableCapacity(capacityVO.getAvailableCapacity()); originalCopy.setTotalCapacity(capacityVO.getTotalCapacity()); originalCopy.setAvailablePhysicalCapacity(capacityVO.getAvailablePhysicalCapacity()); originalCopy.setTotalPhysicalCapacity(capacityVO.getTotalPhysicalCapacity()); originalCopy.setSystemUsedCapacity(capacityVO.getSystemUsedCapacity()); } return capacityVO != null; }
Example #6
Source File: JpaUserCredentialStore.java From keycloak with Apache License 2.0 | 6 votes |
CredentialEntity removeCredentialEntity(RealmModel realm, UserModel user, String id) { CredentialEntity entity = em.find(CredentialEntity.class, id, LockModeType.PESSIMISTIC_WRITE); if (!checkCredentialEntity(entity, user)) return null; int currentPriority = entity.getPriority(); List<CredentialEntity> credentials = getStoredCredentialEntities(realm, user); // Decrease priority of all credentials after our for (CredentialEntity cred : credentials) { if (cred.getPriority() > currentPriority) { cred.setPriority(cred.getPriority() - PRIORITY_DIFFERENCE); } } em.remove(entity); em.flush(); return entity; }
Example #7
Source File: JpaLockingStrategy.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
/** * {@inheritDoc} **/ @Override @Transactional(readOnly = false) public void release() { final Lock lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); if (lock == null) { return; } // Only the current owner can release the lock final String owner = lock.getUniqueId(); if (uniqueId.equals(owner)) { lock.setUniqueId(null); lock.setExpirationDate(null); logger.debug("Releasing {} lock held by {}.", applicationId, uniqueId); entityManager.persist(lock); } else { throw new IllegalStateException("Cannot release lock owned by " + owner); } }
Example #8
Source File: JpaTicketRegistry.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
private Ticket getRawTicket(final String ticketId) { try { if (ticketId.startsWith(this.ticketGrantingTicketPrefix)) { return entityManager.find(TicketGrantingTicketImpl.class, ticketId, LockModeType.PESSIMISTIC_WRITE); } return entityManager.find(ServiceTicketImpl.class, ticketId); } catch (final Exception e) { logger.error("Error getting ticket {} from registry.", ticketId, e); } return null; }
Example #9
Source File: RealmAdapter.java From keycloak with Apache License 2.0 | 5 votes |
private RequiredActionProviderEntity getRequiredProviderEntity(String id, boolean readForRemove) { RequiredActionProviderEntity entity = readForRemove ? em.find(RequiredActionProviderEntity.class, id, LockModeType.PESSIMISTIC_WRITE) : em.find(RequiredActionProviderEntity.class, id); if (entity == null) return null; if (!entity.getRealm().equals(getEntity())) return null; return entity; }
Example #10
Source File: JtaEntityManager.java From tomee with Apache License 2.0 | 5 votes |
public void refresh(final Object entity, final LockModeType lockMode, final Map<String, Object> properties) { assertTransactionActive(); final Timer timer = Op.refresh.start(this.timer, this); try { getEntityManager().refresh(entity, lockMode, properties); } finally { timer.stop(); } }
Example #11
Source File: TransactionScopedEntityManager.java From quarkus with Apache License 2.0 | 5 votes |
@Override public LockModeType getLockMode(Object entity) { checkBlocking(); try (EntityManagerResult emr = getEntityManager()) { return emr.em.getLockMode(entity); } }
Example #12
Source File: TransactionScopedEntityManager.java From quarkus with Apache License 2.0 | 5 votes |
@Override public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) { checkBlocking(); try (EntityManagerResult emr = getEntityManager()) { if (!emr.allowModification) { throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE); } emr.em.refresh(entity, lockMode, properties); } }
Example #13
Source File: JPAScopeStore.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void delete(String id) { ScopeEntity scope = entityManager.find(ScopeEntity.class, id, LockModeType.PESSIMISTIC_WRITE); if (scope != null) { this.entityManager.remove(scope); } }
Example #14
Source File: JpaUserProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) { FederatedIdentityEntity federatedIdentity = findFederatedIdentity(federatedUser, federatedIdentityModel.getIdentityProvider(), LockModeType.PESSIMISTIC_WRITE); federatedIdentity.setToken(federatedIdentityModel.getToken()); em.persist(federatedIdentity); em.flush(); }
Example #15
Source File: JtaEntityManager.java From tomee with Apache License 2.0 | 5 votes |
public void refresh(final Object entity, final LockModeType lockMode) { assertTransactionActive(); final Timer timer = Op.refresh.start(this.timer, this); try { getEntityManager().refresh(entity, lockMode); } finally { timer.stop(); } }
Example #16
Source File: JpaUserProvider.java From keycloak with Apache License 2.0 | 5 votes |
public boolean revokeConsentForClient(RealmModel realm, String userId, String clientId) { UserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.PESSIMISTIC_WRITE); if (consentEntity == null) return false; em.remove(consentEntity); em.flush(); return true; }
Example #17
Source File: KontaktEntityListener.java From elexis-3-core with Eclipse Public License 1.0 | 5 votes |
/** * Finds the current patient number, checks for uniqueness, retrieves it and * increments by one * * @return */ private int findAndIncrementPatientNr(){ int ret = 0; EntityManager em = (EntityManager) ElexisEntityManagerServiceHolder.getEntityManager() .getEntityManager(false); try { em.getTransaction().begin(); Config patNr = em.find(Config.class, "PatientNummer"); if (patNr == null) { Config patNrConfig = new Config(); patNrConfig.setParam("PatientNummer"); patNrConfig.setWert("1"); em.persist(patNrConfig); ret = 1; } else { em.lock(patNr, LockModeType.PESSIMISTIC_WRITE); ret = Integer.parseInt(patNr.getWert()); ret += 1; while (true) { TypedQuery<Kontakt> query = em.createNamedQuery("Kontakt.code", Kontakt.class); query.setParameter("code", Integer.toString(ret)); List<Kontakt> results = query.getResultList(); if (results.isEmpty()) { break; } else { ret += 1; } } patNr.setWert(Integer.toString(ret)); } em.getTransaction().commit(); return ret; } finally { ElexisEntityManagerServiceHolder.getEntityManager().closeEntityManager(em); } }
Example #18
Source File: CommandEntityRepository.java From txle with Apache License 2.0 | 5 votes |
@Lock(LockModeType.OPTIMISTIC) @Query(value = "SELECT * FROM Command AS c " + "WHERE c.eventId IN (" + " SELECT MAX(c1.eventId) FROM Command AS c1 " + " INNER JOIN Command AS c2 on c1.globalTxId = c2.globalTxId" + " WHERE c1.status = 'NEW' " + " GROUP BY c1.globalTxId " + " HAVING MAX( CASE c2.status WHEN 'PENDING' THEN 1 ELSE 0 END ) = 0) " // + "ORDER BY c.eventId ASC LIMIT 1", nativeQuery = true)// 'LIMIT 1' made an effect on performance, and Compensation Command is always executed one by one. So, we canceled 'LIMIT 1'. + "ORDER BY c.eventId ASC", nativeQuery = true) // 查询某全局事务没有PENDING状态且为NEW状态的Command List<Command> findFirstGroupByGlobalTxIdWithoutPendingOrderByIdDesc();
Example #19
Source File: CategoryRepositoryImpl.java From wallride with Apache License 2.0 | 5 votes |
@Override public void lock(long id) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<Category> root = query.from(Category.class); query.select(root.get(Category_.id)); query.where(cb.equal(root.get(Category_.id), id)); entityManager.createQuery(query).setLockMode(LockModeType.PESSIMISTIC_WRITE).getSingleResult(); }
Example #20
Source File: JpaUserFederatedStorageProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void addConsent(RealmModel realm, String userId, UserConsentModel consent) { createIndex(realm, userId); String clientId = consent.getClient().getId(); FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.NONE); if (consentEntity != null) { throw new ModelDuplicateException("Consent already exists for client [" + clientId + "] and user [" + userId + "]"); } consentEntity = new FederatedUserConsentEntity(); consentEntity.setId(KeycloakModelUtils.generateId()); consentEntity.setUserId(userId); StorageId clientStorageId = new StorageId(clientId); if (clientStorageId.isLocal()) { consentEntity.setClientId(clientId); } else { consentEntity.setClientStorageProvider(clientStorageId.getProviderId()); consentEntity.setExternalClientId(clientStorageId.getExternalId()); } consentEntity.setRealmId(realm.getId()); consentEntity.setStorageProviderId(new StorageId(userId).getProviderId()); long currentTime = Time.currentTimeMillis(); consentEntity.setCreatedDate(currentTime); consentEntity.setLastUpdatedDate(currentTime); em.persist(consentEntity); em.flush(); updateGrantedConsentEntity(consentEntity, consent); }
Example #21
Source File: ApplicationRepository.java From steady with Apache License 2.0 | 5 votes |
/** * Finds the applications whose dependencies include constructs from the given list. * Note: the outer select a was added because the lock does not allow the use of "distinct" and we want to avoid to update the same application multiple times in the subsequent update query * * @param listOfConstructs list of {@link ConstructId} * @return list of {@link Application} */ @Lock(LockModeType.PESSIMISTIC_WRITE) @Transactional @Query("select a from Application a where a in" + "( SELECT distinct d.app FROM Dependency d " + " JOIN " + " d.lib l" + " JOIN " + " l.constructs lc " + " WHERE lc IN :listOfConstructs " + " AND (NOT lc.type='PACK' " // Java + Python exception + " OR NOT EXISTS (SELECT 1 FROM ConstructChange cc1 JOIN cc1.constructId c1 WHERE c1 IN :listOfConstructs AND NOT c1.type='PACK' AND NOT c1.qname LIKE '%test%' AND NOT c1.qname LIKE '%Test%' and NOT cc1.constructChangeType='ADD') ) " + " AND NOT (lc.type='MODU' AND (lc.qname='setup' OR lc.qname='tests' OR lc.qname='test.__init__')) )" // Python-specific exception: setup.py is virtually everywhere, considering it would bring far too many FPs. Similarly tests.py originates such a generic module that would bring up too many FPs ) List<Application> findAppsByCC(@Param("listOfConstructs") List<ConstructId> listOfConstructs);
Example #22
Source File: LocalStorageBase.java From zstack with Apache License 2.0 | 5 votes |
@Transactional protected void returnStorageCapacityToHost(String hostUuid, long size) { String sql = "select ref from LocalStorageHostRefVO ref where ref.hostUuid = :huuid and ref.primaryStorageUuid = :primaryStorageUuid"; TypedQuery<LocalStorageHostRefVO> q = dbf.getEntityManager().createQuery(sql, LocalStorageHostRefVO.class); q.setParameter("huuid", hostUuid); q.setParameter("primaryStorageUuid", self.getUuid()); q.setLockMode(LockModeType.PESSIMISTIC_WRITE); List<LocalStorageHostRefVO> refs = q.getResultList(); if (refs.isEmpty()) { throw new CloudRuntimeException(String.format("cannot find host[uuid: %s] of local primary storage[uuid: %s]", hostUuid, self.getUuid())); } LocalStorageHostRefVO ref = refs.get(0); LocalStorageHostCapacityStruct s = new LocalStorageHostCapacityStruct(); s.setSizeBeforeOverProvisioning(size); s.setHostUuid(hostUuid); s.setLocalStorage(getSelfInventory()); s.setSize(size); for (LocalStorageReturnHostCapacityExtensionPoint ext : pluginRgty.getExtensionList( LocalStorageReturnHostCapacityExtensionPoint.class)) { ext.beforeReturnLocalStorageCapacityOnHost(s); } ref.setAvailableCapacity(ref.getAvailableCapacity() + s.getSize()); dbf.getEntityManager().merge(ref); }
Example #23
Source File: CdiQueryInvocationContext.java From deltaspike with Apache License 2.0 | 5 votes |
private LockModeType extractLockMode() { org.apache.deltaspike.data.api.Query query = getRepositoryMethodMetadata().getQuery(); if (query != null && query.lock() != LockModeType.NONE) { return query.lock(); } return null; }
Example #24
Source File: JpaUserFederatedStorageProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) { createIndex(realm, userId); String clientId = consent.getClient().getId(); FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(userId, clientId, LockModeType.PESSIMISTIC_WRITE); if (consentEntity == null) { throw new ModelException("Consent not found for client [" + clientId + "] and user [" + userId + "]"); } updateGrantedConsentEntity(consentEntity, consent); }
Example #25
Source File: JpaUserSessionPersisterProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void removeClientSession(String userSessionId, String clientUUID, boolean offline) { String offlineStr = offlineToString(offline); StorageId clientStorageId = new StorageId(clientUUID); String clientId = PersistentClientSessionEntity.EXTERNAL; String clientStorageProvider = PersistentClientSessionEntity.LOCAL; String externalId = PersistentClientSessionEntity.LOCAL; if (clientStorageId.isLocal()) { clientId = clientUUID; } else { clientStorageProvider = clientStorageId.getProviderId(); externalId = clientStorageId.getExternalId(); } PersistentClientSessionEntity sessionEntity = em.find(PersistentClientSessionEntity.class, new PersistentClientSessionEntity.Key(userSessionId, clientId, clientStorageProvider, externalId, offlineStr), LockModeType.PESSIMISTIC_WRITE); if (sessionEntity != null) { em.remove(sessionEntity); // Remove userSession if it was last clientSession List<PersistentClientSessionEntity> clientSessions = getClientSessionsByUserSession(sessionEntity.getUserSessionId(), offline); if (clientSessions.size() == 0) { offlineStr = offlineToString(offline); PersistentUserSessionEntity userSessionEntity = em.find(PersistentUserSessionEntity.class, new PersistentUserSessionEntity.Key(sessionEntity.getUserSessionId(), offlineStr), LockModeType.PESSIMISTIC_WRITE); if (userSessionEntity != null) { em.remove(userSessionEntity); } } em.flush(); } }
Example #26
Source File: QueryCacheTestClass.java From cuba with Apache License 2.0 | 5 votes |
@Test public void testLockModeQuery() throws Exception { appender.clearMessages(); assertEquals(0, queryCache.size()); getResultListUserByLoginNamed(user, false, null, query -> query.setLockMode(LockModeType.PESSIMISTIC_READ)); assertEquals(0, queryCache.size()); }
Example #27
Source File: LockModeTypeHelper.java From lams with GNU General Public License v2.0 | 5 votes |
public static LockMode interpretLockMode(Object value) { if ( value == null ) { return LockMode.NONE; } if ( LockMode.class.isInstance( value ) ) { return (LockMode) value; } else if ( LockModeType.class.isInstance( value ) ) { return getLockMode( (LockModeType) value ); } else if ( String.class.isInstance( value ) ) { // first try LockMode name LockMode lockMode = LockMode.valueOf( (String) value ); if ( lockMode == null ) { try { lockMode = getLockMode( LockModeType.valueOf( (String) value ) ); } catch ( Exception ignore ) { } } if ( lockMode != null ) { return lockMode; } } throw new IllegalArgumentException( "Unknown lock mode source : " + value ); }
Example #28
Source File: ClientScopeAdapter.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void deleteScopeMapping(RoleModel role) { TypedQuery<ClientScopeRoleMappingEntity> query = getRealmScopeMappingQuery(role); query.setLockMode(LockModeType.PESSIMISTIC_WRITE); List<ClientScopeRoleMappingEntity> results = query.getResultList(); if (results.size() == 0) return; for (ClientScopeRoleMappingEntity entity : results) { em.remove(entity); } }
Example #29
Source File: QueryResultTest.java From deltaspike with Apache License 2.0 | 5 votes |
@Test public void should_page_result() { // given final String name = "testPageResult"; builder.createSimple(name, Integer.valueOf(99)); builder.createSimple(name, Integer.valueOf(22)); builder.createSimple(name, Integer.valueOf(22)); builder.createSimple(name, Integer.valueOf(22)); builder.createSimple(name, Integer.valueOf(56)); builder.createSimple(name, Integer.valueOf(123)); // when List<Simple> result = repo.findByName(name) .hint("javax.persistence.query.timeout", 10000) .lockMode(LockModeType.NONE) .flushMode(FlushModeType.COMMIT) .orderDesc(Simple_.counter) .firstResult(2) .maxResults(2) .getResultList(); // then assertNotNull(result); assertFalse(result.isEmpty()); assertEquals(2, result.size()); }
Example #30
Source File: JpaLockingStrategy.java From springboot-shiro-cas-mybatis with MIT License | 5 votes |
/** * {@inheritDoc} **/ @Override @Transactional(readOnly = false) public boolean acquire() { Lock lock; try { lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); } catch (final PersistenceException e) { logger.debug("{} failed querying for {} lock.", uniqueId, applicationId, e); return false; } boolean result = false; if (lock != null) { final DateTime expDate = new DateTime(lock.getExpirationDate()); if (lock.getUniqueId() == null) { // No one currently possesses lock logger.debug("{} trying to acquire {} lock.", uniqueId, applicationId); result = acquire(entityManager, lock); } else if (new DateTime().isAfter(expDate)) { // Acquire expired lock regardless of who formerly owned it logger.debug("{} trying to acquire expired {} lock.", uniqueId, applicationId); result = acquire(entityManager, lock); } } else { // First acquisition attempt for this applicationId logger.debug("Creating {} lock initially held by {}.", applicationId, uniqueId); result = acquire(entityManager, new Lock()); } return result; }