org.hibernate.LockMode Java Examples

The following examples show how to use org.hibernate.LockMode. 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: CascadeLockUnidirectionalOneToManyTest.java    From high-performance-java-persistence with Apache License 2.0 7 votes vote down vote up
@Test
public void testCascadeLockOnDetachedEntityUninitializedWithScope() {
    LOGGER.info("Test lock cascade for detached entity with scope");

    //Load the Post entity, which will become detached
    Post post = doInJPA(entityManager -> (Post) entityManager.find(Post.class, 1L));

    doInJPA(entityManager -> {
        LOGGER.info("Reattach and lock entity with associations not initialized");
        entityManager.unwrap(Session.class)
                .buildLockRequest(
                        new LockOptions(LockMode.PESSIMISTIC_WRITE))
                .setScope(true)
                .lock(post);

        LOGGER.info("Check entities are reattached");
        //The Post entity graph is attached
        containsPost(entityManager, post, true);
    });
}
 
Example #2
Source File: TwoPhaseLoad.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void addUninitializedCachedEntity(
		final EntityKey key, 
		final Object object, 
		final EntityPersister persister, 
		final LockMode lockMode,
		final boolean lazyPropertiesAreUnfetched,
		final Object version,
		final SessionImplementor session
) {
	session.getPersistenceContext().addEntity(
			object, 
			Status.LOADING, 
			null, 
			key, 
			version, 
			lockMode, 
			true, 
			persister, 
			false, 
			lazyPropertiesAreUnfetched
		);
}
 
Example #3
Source File: FollowOnLockingTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpgradeSkipLockedOrderBy() {
    LOGGER.info("Test lock contention");
    doInJPA(entityManager -> {
        List<Post> pendingPosts = entityManager.createQuery(
            "select p " +
            "from Post p " +
            "where p.status = :status " +
            "order by p.id ",
            Post.class)
        .setParameter("status", PostStatus.PENDING)
        .setFirstResult(2)
        .unwrap(org.hibernate.Query.class)
        .setLockOptions(new LockOptions(LockMode.UPGRADE_SKIPLOCKED))
        .list();

        assertEquals(3, pendingPosts.size());
    });
}
 
Example #4
Source File: ReactiveSessionTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void reactiveQueryWithLock(TestContext context) {
	final GuineaPig expectedPig = new GuineaPig( 5, "Aloi" );
	test(
			context,
			populateDB()
					.thenCompose( v -> getSessionFactory().withTransaction(
							(session, tx) -> session.createQuery( "from GuineaPig pig", GuineaPig.class)
									.setLockMode(LockMode.PESSIMISTIC_WRITE)
									.getSingleResult()
									.thenAccept( actualPig -> {
										assertThatPigsAreEqual( context, expectedPig, actualPig );
										context.assertEquals( session.getLockMode( actualPig ), LockMode.PESSIMISTIC_WRITE );
									} )
							)
					)
	);
}
 
Example #5
Source File: QueryLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param lockModes a collection of lock modes specified dynamically via the Query interface
 */
protected LockMode[] getLockModes(Map lockModes) {

	if ( lockModes==null || lockModes.size()==0 ) {
		return defaultLockModes;
	}
	else {
		// unfortunately this stuff can't be cached because
		// it is per-invocation, not constant for the
		// QueryTranslator instance

		LockMode[] lockModeArray = new LockMode[entityAliases.length];
		for ( int i = 0; i < entityAliases.length; i++ ) {
			LockMode lockMode = (LockMode) lockModes.get( entityAliases[i] );
			if ( lockMode == null ) {
				//NONE, because its the requested lock mode, not the actual!
				lockMode = LockMode.NONE;
			}
			lockModeArray[i] = lockMode;
		}
		return lockModeArray;
	}
}
 
Example #6
Source File: ProbandServiceImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected ProbandAddressOutVO handleDeleteProbandAddress(
		AuthenticationVO auth, Long probandAddressId) throws Exception {
	ProbandAddressDao addressDao = this.getProbandAddressDao();
	ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, addressDao);
	Proband proband = address.getProband();
	this.getProbandDao().lock(proband, LockMode.PESSIMISTIC_WRITE);
	ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address);
	if (!result.isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_ADDRESS);
	}
	ServiceUtil.checkProbandLocked(proband);
	if (address.isWireTransfer() && addressDao.getCount(address.getProband().getId(), null, null, null) > 1) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DELETE_WIRE_TRANSFER_PROBAND_ADDRESS);
	}
	proband.removeAddresses(address);
	address.setProband(null);
	addressDao.remove(address);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_DELETED, result, null, this.getJournalEntryDao());
	return result;
}
 
Example #7
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T load(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<T>() {
		@Override
		@SuppressWarnings("unchecked")
		public T doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return (T) session.load(entityClass, id, lockMode);
			}
			else {
				return (T) session.load(entityClass, id);
			}
		}
	});
}
 
Example #8
Source File: BatchingEntityLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static UniqueEntityLoader createBatchingEntityLoader(
	final OuterJoinLoadable persister,
	final int maxBatchSize,
	final LockMode lockMode,
	final SessionFactoryImplementor factory,
	final Map enabledFilters)
throws MappingException {

	if ( maxBatchSize>1 ) {
		int[] batchSizesToCreate = ArrayHelper.getBatchSizes(maxBatchSize);
		Loader[] loadersToCreate = new Loader[ batchSizesToCreate.length ];
		for ( int i=0; i<batchSizesToCreate.length; i++ ) {
			loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockMode, factory, enabledFilters);
		}
		return new BatchingEntityLoader(persister, batchSizesToCreate, loadersToCreate);
	}
	else {
		return new EntityLoader(persister, lockMode, factory, enabledFilters);
	}
}
 
Example #9
Source File: ImmutableEntityEntry.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Custom deserialization routine used during deserialization of a
 * Session/PersistenceContext for increased performance.
 *
 * @param ois The stream from which to read the entry.
 * @param persistenceContext The context being deserialized.
 *
 * @return The deserialized EntityEntry
 *
 * @throws java.io.IOException If a stream error occurs
 * @throws ClassNotFoundException If any of the classes declared in the stream
 * cannot be found
 */
public static EntityEntry deserialize(
		ObjectInputStream ois,
		PersistenceContext persistenceContext) throws IOException, ClassNotFoundException {
	String previousStatusString;
	return new ImmutableEntityEntry(
			persistenceContext.getSession().getFactory(),
			(String) ois.readObject(),
			(Serializable) ois.readObject(),
			Status.valueOf( (String) ois.readObject() ),
			( previousStatusString = (String) ois.readObject() ).length() == 0
					? null
					: Status.valueOf( previousStatusString ),
			(Object[]) ois.readObject(),
			(Object[]) ois.readObject(),
			ois.readObject(),
			LockMode.valueOf( (String) ois.readObject() ),
			ois.readBoolean(),
			ois.readBoolean(),
			null
	);
}
 
Example #10
Source File: AbstractEntityInsertAction.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Make the entity "managed" by the persistence context.
 */
public final void makeEntityManaged() {
	nullifyTransientReferencesIfNotAlready();
	final Object version = Versioning.getVersion( getState(), getPersister() );
	getSession().getPersistenceContext().addEntity(
			getInstance(),
			( getPersister().isMutable() ? Status.MANAGED : Status.READ_ONLY ),
			getState(),
			getEntityKey(),
			version,
			LockMode.WRITE,
			isExecuted,
			getPersister(),
			isVersionIncrementDisabled
	);
}
 
Example #11
Source File: JobCollisionFinder.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected ROOT aquireWriteLock(JobAddVO in) throws ServiceException {
	switch (module) {
		case TRIAL_JOB:
			return (ROOT) trialDao.load(in.getTrialId(), LockMode.PESSIMISTIC_WRITE);
		case PROBAND_JOB:
			return (ROOT) probandDao.load(in.getProbandId(), LockMode.PESSIMISTIC_WRITE);
		case INPUT_FIELD_JOB:
			return (ROOT) inputFieldDao.load(in.getInputFieldId(), LockMode.PESSIMISTIC_WRITE);
		case INVENTORY_CRITERIA_JOB:
		case STAFF_CRITERIA_JOB:
		case COURSE_CRITERIA_JOB:
		case TRIAL_CRITERIA_JOB:
		case INPUT_FIELD_CRITERIA_JOB:
		case PROBAND_CRITERIA_JOB:
		case USER_CRITERIA_JOB:
		case MASS_MAIL_CRITERIA_JOB:
			return (ROOT) criteriaDao.load(in.getCriteriaId(), LockMode.PESSIMISTIC_WRITE);
		default:
			// not supported for now...
			throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.UNSUPPORTED_JOB_MODULE, DefaultMessages.UNSUPPORTED_JOB_MODULE,
					new Object[] { module.toString() }));
	}
}
 
Example #12
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public <T> T load(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<T>() {
		@Override
		@SuppressWarnings("unchecked")
		public T doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return (T) session.load(entityClass, id, lockMode);
			}
			else {
				return (T) session.load(entityClass, id);
			}
		}
	});
}
 
Example #13
Source File: DefaultReactiveLoadEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<Object> doOnLoad(
		final EntityPersister persister,
		final LoadEvent event,
		final LoadEventListener.LoadType loadType) {

	final EventSource session = event.getSession();
	final EntityKey keyToLoad = session.generateEntityKey( event.getEntityId(), persister );
	if ( loadType.isNakedEntityReturned() ) {
		//do not return a proxy!
		//(this option indicates we are initializing a proxy)
		return load( event, persister, keyToLoad, loadType );
	}
	//return a proxy if appropriate
	else if ( event.getLockMode() == LockMode.NONE ) {
		return proxyOrLoad( event, persister, keyToLoad, loadType );
	}
	else {
		return lockAndLoad( event, persister, keyToLoad, loadType, session );
	}
}
 
Example #14
Source File: FileServiceImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @see org.phoenixctms.ctsms.service.shared.FileService#updateFile(FileInVO)
 */
@Override
protected FileOutVO handleUpdateFile(AuthenticationVO auth, FileInVO modifiedFile)
		throws Exception {
	FileDao fileDao = this.getFileDao();
	File originalFile = CheckIDUtil.checkFileId(modifiedFile.getId(), fileDao, LockMode.UPGRADE_NOWAIT);
	checkFileInput(modifiedFile);
	if (!fileDao.toFileOutVO(originalFile).isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_FILE);
	}
	FileOutVO original = fileDao.toFileOutVO(originalFile);
	fileDao.evict(originalFile);
	File file = fileDao.fileInVOToEntity(modifiedFile);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalFile, file, now, user);
	fileDao.update(file);
	return addFileUpdatedJournalEntry(file, original, now, user);
}
 
Example #15
Source File: LoadEvent.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private LoadEvent(
		Serializable entityId,
		String entityClassName,
		Object instanceToLoad,
		LockMode lockMode,
		boolean isAssociationFetch,
		EventSource source) {
	this( entityId, entityClassName, instanceToLoad,
			lockMode == DEFAULT_LOCK_MODE ? DEFAULT_LOCK_OPTIONS : new LockOptions().setLockMode( lockMode ),
			isAssociationFetch, source );
}
 
Example #16
Source File: Loader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected LockMode determineFollowOnLockMode(LockOptions lockOptions) {
	final LockMode lockModeToUse = lockOptions.findGreatestLockMode();

	if ( lockOptions.hasAliasSpecificLockModes() ) {
		if ( lockOptions.getLockMode() == LockMode.NONE && lockModeToUse == LockMode.NONE ) {
			return lockModeToUse;
		}
		else {
			LOG.aliasSpecificLockingWithFollowOnLocking( lockModeToUse );
		}
	}
	return lockModeToUse;
}
 
Example #17
Source File: Category.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * @return A set containing parents (supercategories) of this category.
 */
public Set<Category> getParents() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getInLinks());
    session.getTransaction().commit();

    Set<Category> categories = new HashSet<Category>();
    for (int pageID : tmpSet) {
        categories.add(this.wiki.getCategory(pageID));
    }
    return categories;
}
 
Example #18
Source File: Category.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * @return A set containing the IDs of the parents of this category.
 */
public Set<Integer> getParentIDs() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getInLinks());
    session.getTransaction().commit();
    return tmpSet;
}
 
Example #19
Source File: StatefulPersistenceContext.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generates an appropriate EntityEntry instance and adds it 
 * to the event source's internal caches.
 */
public EntityEntry addEntry(
		final Object entity,
		final Status status,
		final Object[] loadedState,
		final Object rowId,
		final Serializable id,
		final Object version,
		final LockMode lockMode,
		final boolean existsInDatabase,
		final EntityPersister persister,
		final boolean disableVersionIncrement, 
		boolean lazyPropertiesAreUnfetched) {
	
	EntityEntry e = new EntityEntry(
			status,
			loadedState,
			rowId,
			id,
			version,
			lockMode,
			existsInDatabase,
			persister,
			session.getEntityMode(),
			disableVersionIncrement,
			lazyPropertiesAreUnfetched
		);
	entityEntries.put(entity, e);
	
	setHasNonReadOnlyEnties(status);
	return e;
}
 
Example #20
Source File: HibernateTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void refresh(final Object entity, @Nullable final LockMode lockMode) throws DataAccessException {
	executeWithNativeSession(session -> {
		if (lockMode != null) {
			session.refresh(entity, new LockOptions(lockMode));
		}
		else {
			session.refresh(entity);
		}
		return null;
	});
}
 
Example #21
Source File: HibernateTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void lock(final Object entity, final LockMode lockMode) throws DataAccessException {
	executeWithNativeSession(session -> {
		session.buildLockRequest(new LockOptions(lockMode)).lock(entity);
		return null;
	});
}
 
Example #22
Source File: OptimisticLockingBidirectionalChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
public void onPersist(PersistEvent event) throws HibernateException {
    final Object entity = event.getObject();

    if(entity instanceof RootAware) {
        RootAware rootAware = (RootAware) entity;
        Object root = rootAware.root();
        event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);

        LOGGER.info("Incrementing {} entity version because a {} child entity has been inserted", root, entity);
    }
}
 
Example #23
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
	executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			checkWriteOperationAllowed(session);
			session.update(entity);
			if (lockMode != null) {
				session.buildLockRequest(new LockOptions(lockMode)).lock(entity);
			}
			return null;
		}
	});
}
 
Example #24
Source File: RefreshEvent.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public RefreshEvent(Object object, LockMode lockMode, EventSource source) {
	this(object, source);
	if (lockMode == null) {
		throw new IllegalArgumentException("Attempt to generate refresh event with null lock mode");
	}
	this.lockOptions.setLockMode(lockMode);
}
 
Example #25
Source File: NativeSQLQueryJoinReturn.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Construct a return descriptor representing some form of fetch.
 *
 * @param alias The result alias
 * @param ownerAlias The owner's result alias
 * @param ownerProperty The owner's property representing the thing to be fetched
 * @param propertyResults Any user-supplied column->property mappings
 * @param lockMode The lock mode to apply
 */
public NativeSQLQueryJoinReturn(
		String alias,
		String ownerAlias,
		String ownerProperty,
		Map propertyResults,
		LockMode lockMode) {
	super( alias, propertyResults, lockMode );
	this.ownerAlias = ownerAlias;
	this.ownerProperty = ownerProperty;
}
 
Example #26
Source File: CollectionReturn.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public CollectionReturn(
		String alias,
		String ownerEntityName,
		String ownerProperty,
		CollectionAliases collectionAliases,
		EntityAliases elementEntityAliases,
		LockMode lockMode) {
	super( alias, lockMode );
	this.ownerEntityName = ownerEntityName;
	this.ownerProperty = ownerProperty;
	this.collectionAliases = collectionAliases;
	this.elementEntityAliases = elementEntityAliases;
}
 
Example #27
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testLockWithEntityName() throws HibernateException {
	TestBean tb = new TestBean();
	hibernateTemplate.lock("myEntity", tb, LockMode.WRITE);
	verify(session).lock("myEntity", tb, LockMode.WRITE);
	verify(session).flush();
	verify(session).close();
}
 
Example #28
Source File: AbstractTransactSQLDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String applyLocksToSql(String sql, LockOptions aliasedLockOptions, Map<String, String[]> keyColumnNames) {
	// TODO:  merge additional lockoptions support in Dialect.applyLocksToSql
	final Iterator itr = aliasedLockOptions.getAliasLockIterator();
	final StringBuilder buffer = new StringBuilder( sql );

	while ( itr.hasNext() ) {
		final Map.Entry entry = (Map.Entry) itr.next();
		final LockMode lockMode = (LockMode) entry.getValue();
		if ( lockMode.greaterThan( LockMode.READ ) ) {
			final String alias = (String) entry.getKey();
			int start = -1;
			int end = -1;
			if ( sql.endsWith( " " + alias ) ) {
				start = ( buffer.length() - alias.length() );
				end = start + alias.length();
			}
			else {
				int position = buffer.indexOf( " " + alias + " " );
				if ( position <= -1 ) {
					position = buffer.indexOf( " " + alias + "," );
				}
				if ( position > -1 ) {
					start = position + 1;
					end = start + alias.length();
				}
			}

			if ( start > -1 ) {
				final String lockHint = appendLockHint( aliasedLockOptions, alias );
				buffer.replace( start, end, lockHint );
			}
		}
	}
	return buffer.toString();
}
 
Example #29
Source File: BaseDao.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public O internalGetById(final Serializable id)
{
  if (id == null) {
    return null;
  }
  final O obj = getHibernateTemplate().get(clazz, id, LockMode.READ);
  afterLoad(obj);
  return obj;
}
 
Example #30
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(final Object entity, final LockMode lockMode) throws DataAccessException {
	executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			checkWriteOperationAllowed(session);
			if (lockMode != null) {
				session.buildLockRequest(new LockOptions(lockMode)).lock(entity);
			}
			session.delete(entity);
			return null;
		}
	});
}