类javax.persistence.LockModeType源码实例Demo

下面列出了怎么用javax.persistence.LockModeType的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: zstack   文件: PrimaryStorageCapacityUpdater.java
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;
}
 
@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();
}
 
源代码3 项目: keycloak   文件: JpaUserCredentialStore.java
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;
}
 
/**
 * {@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);
    }
}
 
源代码5 项目: lams   文件: LockModeConverter.java
/**
 * 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 );
}
 
/** {@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);
    }
}
 
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);
}
 
源代码8 项目: txle   文件: CommandEntityRepository.java
@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();
 
源代码9 项目: quarkus   文件: TransactionScopedEntityManager.java
@Override
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        return emr.em.find(entityClass, primaryKey, lockMode);
    }
}
 
源代码10 项目: tomee   文件: JtaEntityManager.java
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();
    }
}
 
源代码11 项目: keycloak   文件: RealmAdapter.java
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;
}
 
源代码12 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码13 项目: quarkus   文件: TransactionScopedEntityManager.java
@Override
public LockModeType getLockMode(Object entity) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        return emr.em.getLockMode(entity);
    }
}
 
源代码14 项目: keycloak   文件: JpaUserProvider.java
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;
}
 
源代码15 项目: wallride   文件: CategoryRepositoryImpl.java
@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();
}
 
源代码16 项目: tomee   文件: JtaEntityManager.java
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();
    }
}
 
源代码17 项目: elexis-3-core   文件: KontaktEntityListener.java
/**
 * 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);
	}
}
 
源代码18 项目: keycloak   文件: JpaUserFederatedStorageProvider.java
@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);

}
 
源代码19 项目: steady   文件: ApplicationRepository.java
/**
 * 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);
 
源代码20 项目: zstack   文件: LocalStorageBase.java
@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);
}
 
源代码21 项目: keycloak   文件: JpaUserFederatedStorageProvider.java
@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);

}
 
源代码22 项目: cuba   文件: QueryCacheTestClass.java
@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());
}
 
源代码23 项目: lams   文件: LockModeTypeHelper.java
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 );
}
 
源代码24 项目: keycloak   文件: ClientScopeAdapter.java
@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);
    }
}
 
源代码25 项目: deltaspike   文件: QueryResultTest.java
@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());
}
 
/**
 * {@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;
}
 
源代码27 项目: keycloak   文件: JpaUserSessionPersisterProvider.java
@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();
    }
}
 
源代码28 项目: deltaspike   文件: CdiQueryInvocationContext.java
private LockModeType extractLockMode()
{
    org.apache.deltaspike.data.api.Query query = getRepositoryMethodMetadata().getQuery();
    if (query != null && query.lock() != LockModeType.NONE)
    {
        return query.lock();
    }

    return null;
}
 
源代码29 项目: keycloak   文件: JpaUserProvider.java
@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();
}
 
源代码30 项目: cas4.0.x-server-wechat   文件: JpaTicketRegistry.java
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;
}
 
 类所在包
 同包方法