org.hibernate.LockOptions Java Examples

The following examples show how to use org.hibernate.LockOptions. 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: PessimisticReadSelectLockingStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected String generateLockString(int lockTimeout) {
	final SessionFactoryImplementor factory = getLockable().getFactory();
	final LockOptions lockOptions = new LockOptions( getLockMode() );
	lockOptions.setTimeOut( lockTimeout );
	final SimpleSelect select = new SimpleSelect( factory.getDialect() )
			.setLockOptions( lockOptions )
			.setTableName( getLockable().getRootTableName() )
			.addColumn( getLockable().getRootTableIdentifierColumnNames()[0] )
			.addCondition( getLockable().getRootTableIdentifierColumnNames(), "=?" );
	if ( getLockable().isVersioned() ) {
		select.addCondition( getLockable().getVersionColumnName(), "=?" );
	}
	if ( factory.getSessionFactoryOptions().isCommentsEnabled() ) {
		select.setComment( getLockMode() + " lock " + getLockable().getEntityName() );
	}
	return select.toStatementString();
}
 
Example #2
Source File: Page.java    From dkpro-jwpl with Apache License 2.0 6 votes vote down vote up
/**
 * @return The a set of categories that this page belongs to.
 */
public Set<Category> getCategories()
{
	Session session = this.wiki.__getHibernateSession();
	session.beginTransaction();
	session.buildLockRequest(LockOptions.NONE).lock(hibernatePage);
	Set<Integer> tmp = new UnmodifiableArraySet<Integer>(hibernatePage.getCategories());
	session.getTransaction().commit();

	Set<Category> categories = new HashSet<Category>();
	for (int pageID : tmp) {
		categories.add(wiki.getCategory(pageID));
	}

	return categories;
}
 
Example #3
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(final Class<T> entityClass, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<T>() {
		@Override
		public T doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return session.get(entityClass, id, new LockOptions(lockMode));
			}
			else {
				return session.get(entityClass, id);
			}
		}
	});
}
 
Example #4
Source File: LockModePessimisticForceIncrementTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentPessimisticForceIncrementLockingFailFast() throws InterruptedException {
    LOGGER.info("Test Concurrent PESSIMISTIC_FORCE_INCREMENT Lock Mode fail fast");
    doInTransaction(session -> {
        try {
            Repository repository = (Repository) session.get(Repository.class, 1L);

            executeSync(() -> {
                doInTransaction(_session -> {
                    Repository _repository = (Repository) _session.get(Repository.class, 1L);
                    _session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_FORCE_INCREMENT)).lock(_repository);
                    Commit _commit = new Commit(_repository);
                    _commit.getChanges().add(new Change("index.html", "0a1,2..."));
                    _session.persist(_commit);
                    _session.flush();
                });
            });
            session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_FORCE_INCREMENT)).lock(repository);
            fail("Should have thrown StaleObjectStateException!");
        } catch (StaleObjectStateException expected) {
            LOGGER.info("Failure: ", expected);
        }
    });
}
 
Example #5
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, new LockOptions(lockMode));
			}
			else {
				return (T) session.load(entityClass, id);
			}
		}
	});
}
 
Example #6
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void delete(List<E> entityCollection) {
	Session session = getCurrentSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		for (E e: entityCollection) {
			session.buildLockRequest(LockOptions.UPGRADE).lock(e);
			session.delete(e);
			session.flush();
			session.evict(e);
		}
		if (!tx.wasCommitted()) tx.commit();
	} catch (Exception ex) {
		logger.error("Delete list failed", ex);
		tx.rollback();
		throw new HibernateException("Delete list failed");
	}
}
 
Example #7
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object load(final String entityName, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return session.load(entityName, id, new LockOptions(lockMode));
			}
			else {
				return session.load(entityName, id);
			}
		}
	});
}
 
Example #8
Source File: FollowOnLockingTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testPessimisticWrite() {
    LOGGER.info("Test lock contention");
    doInJPA(entityManager -> {
        List<Post> pendingPosts = entityManager.createQuery(
            "select p " +
            "from Post p " +
            "where p.status = :status",
            Post.class)
        .setParameter("status", PostStatus.PENDING)
        .setMaxResults(5)
        //.setLockMode(LockModeType.PESSIMISTIC_WRITE)
        .unwrap(org.hibernate.Query.class)
        .setLockOptions(new LockOptions(LockMode.PESSIMISTIC_WRITE).setTimeOut(LockOptions.SKIP_LOCKED))
        .list();

        assertEquals(5, pendingPosts.size());
    });
}
 
Example #9
Source File: ReactivePlanEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public CompletionStage<Object> load(Serializable id, Object optionalObject,
									SharedSessionContractImplementor session,
									LockOptions lockOptions, Boolean readOnly) {

	final QueryParameters parameters = buildQueryParameters( id, optionalObject, lockOptions, readOnly );
	String sql = getStaticLoadQuery().getSqlStatement();

	return doReactiveQueryAndInitializeNonLazyCollections( sql, (SessionImplementor) session, parameters )
			.thenApply( results -> extractEntityResult( results, id ) )
			.handle( (list, err) -> {
				CompletionStages.logSqlException( err,
						() -> "could not load an entity: "
								+ infoString( persister, id, persister.getIdentifierType(), getFactory() ),
						sql
				);
				return CompletionStages.returnOrRethrow( err, list) ;
			} );
}
 
Example #10
Source File: ReactiveDynamicBatchingEntityLoaderBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<List<Object>> performOrderedBatchLoad(
		List<Serializable> idsInBatch,
		LockOptions lockOptions,
		OuterJoinLoadable persister,
		SessionImplementor session) {
	final int batchSize =  idsInBatch.size();
	final ReactiveDynamicBatchingEntityLoader batchingLoader = new ReactiveDynamicBatchingEntityLoader(
			persister,
			batchSize,
			lockOptions,
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);

	final Serializable[] idsInBatchArray = idsInBatch.toArray(new Serializable[0]);
	QueryParameters qp = buildMultiLoadQueryParameters( persister, idsInBatchArray, lockOptions );
	CompletionStage<List<Object>> result = batchingLoader.doEntityBatchFetch(session, qp, idsInBatchArray);
	idsInBatch.clear();
	return result;
}
 
Example #11
Source File: Page.java    From dkpro-jwpl with Apache License 2.0 6 votes vote down vote up
/**
	 * Returns the set of pages that are linked from this page. Outlinks in a page might also point
	 * to non-existing pages. They are not included in the result set. <b>Warning:</b> Do not use
	 * this for getting the number of outlinks with {@link Page#getOutlinks()}.size(). This is too slow. Use
	 * {@link Page#getNumberOfOutlinks()} instead.
	 *
	 * @return The set of pages that are linked from this page.
	 */
	public Set<Page> getOutlinks()
	{
		Session session = wiki.__getHibernateSession();
		session.beginTransaction();
//		session.lock(hibernatePage, LockMode.NONE);
		session.buildLockRequest(LockOptions.NONE).lock(hibernatePage);
		// Have to copy links here since getPage later will close the session.
		Set<Integer> tmpSet = new UnmodifiableArraySet<Integer>(hibernatePage.getOutLinks());
		session.getTransaction().commit();

		Set<Page> pages = new HashSet<Page>();
		for (int pageID : tmpSet) {
			try {
				pages.add(wiki.getPage(pageID));
			}
			catch (WikiApiException e) {
				// Silently ignore if a page could not be found.
				// There may be outlinks pointing to non-existing pages.
			}
		}
		return pages;
	}
 
Example #12
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
		public T doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return session.load(entityClass, id, new LockOptions(lockMode));
			}
			else {
				return session.load(entityClass, id);
			}
		}
	});
}
 
Example #13
Source File: AbstractProducedQuery.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public QueryImplementor setLockOptions(LockOptions lockOptions) {
	this.lockOptions.setLockMode( lockOptions.getLockMode() );
	this.lockOptions.setScope( lockOptions.getScope() );
	this.lockOptions.setTimeOut( lockOptions.getTimeOut() );
	this.lockOptions.setFollowOnLocking( lockOptions.getFollowOnLocking() );
	return this;
}
 
Example #14
Source File: Page.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * The result set may also contain links from non-existing pages. It is in the responsibility of
 * the user to check whether the page exists.
 *
 * @return Returns the IDs of the outLinks of this page.
 */
public Set<Integer> getOutlinkIDs()
{
	Set<Integer> tmpSet = new HashSet<Integer>();

	Session session = wiki.__getHibernateSession();
	session.beginTransaction();
	session.buildLockRequest(LockOptions.NONE).lock(hibernatePage);

	tmpSet.addAll(hibernatePage.getOutLinks());

	session.getTransaction().commit();
	return tmpSet;
}
 
Example #15
Source File: PostgreSQL81Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getReadLockString(String aliases, int timeout) {
	if ( timeout == LockOptions.NO_WAIT ) {
		return String.format( " for share of %s nowait", aliases );
	}
	else {
		return " for share of " + aliases;
	}
}
 
Example #16
Source File: HibernateTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object get(final String entityName, final Serializable id, @Nullable final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(session -> {
		if (lockMode != null) {
			return session.get(entityName, id, new LockOptions(lockMode));
		}
		else {
			return session.get(entityName, id);
		}
	});
}
 
Example #17
Source File: CascadeLockTest.java    From hibernate-master-class with Apache License 2.0 5 votes vote down vote up
@Test
public void testCascadeLockOnManagedEntity() throws InterruptedException {
    LOGGER.info("Test lock cascade for managed entity");
    doInTransaction(session -> {
        Post post = (Post) session.createQuery(
            "select p " +
            "from Post p " +
            "join fetch p.details " +
            "where " +
            "   p.id = :id"
        ).setParameter("id", 1L)
        .uniqueResult();
        session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).setScope(true).lock(post);
    });
}
 
Example #18
Source File: LockModePessimisticReadWriteIntegrationTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Test
public void testPessimisticWriteBlocksPessimisticRead() throws InterruptedException {
    LOGGER.info("Test PESSIMISTIC_WRITE blocks PESSIMISTIC_READ");
    testPessimisticLocking(
            (session, post) -> {
                session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post);
                LOGGER.info("PESSIMISTIC_WRITE acquired");
            },
            (session, post) -> {
                session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_READ)).lock(post);
                LOGGER.info("PESSIMISTIC_READ acquired");
            }
    );
}
 
Example #19
Source File: CriteriaLoader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected LockMode[] getLockModes(LockOptions lockOptions) {
	final String[] entityAliases = getAliases();
	if ( entityAliases == null ) {
		return null;
	}
	final int size = entityAliases.length;
	LockMode[] lockModesArray = new LockMode[size];
	for ( int i=0; i<size; i++ ) {
		LockMode lockMode = lockOptions.getAliasSpecificLockMode( entityAliases[i] );
		lockModesArray[i] = lockMode==null ? lockOptions.getLockMode() : lockMode;
	}
	return lockModesArray;
}
 
Example #20
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.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 #21
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;
		}
	});
}
 
Example #22
Source File: Oracle9iDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getWriteLockString(int timeout) {
	if ( timeout == LockOptions.NO_WAIT ) {
		return " for update nowait";
	}
	else if ( timeout > 0 ) {
		// convert from milliseconds to seconds
		final float seconds = timeout / 1000.0f;
		timeout = Math.round( seconds );
		return " for update wait " + timeout;
	}
	else {
		return " for update";
	}
}
 
Example #23
Source File: HibernateUtil.java    From AlgoTrader with GNU General Public License v2.0 5 votes vote down vote up
public static boolean lock(SessionFactory sessionFactory, Object target) {

		Session session = sessionFactory.getCurrentSession();

		try {
			session.buildLockRequest(LockOptions.NONE).lock(target);
			return true;
		} catch (NonUniqueObjectException e) {
			//  different object with the same identifier value was already associated with the session
			return false;
		}
	}
 
Example #24
Source File: LockModePessimisticForceIncrementTest.java    From hibernate-master-class with Apache License 2.0 5 votes vote down vote up
@Test
public void testPessimisticForceIncrementLocking() throws InterruptedException {
    LOGGER.info("Test Single PESSIMISTIC_FORCE_INCREMENT Lock Mode ");
    doInTransaction(session -> {
        Repository repository = (Repository) session.get(Repository.class, 1L);
        session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_FORCE_INCREMENT)).lock(repository);
        Commit commit = new Commit(repository);
        commit.getChanges().add(new Change("README.txt", "0a1,5..."));
        commit.getChanges().add(new Change("web.xml", "17c17..."));
        session.persist(commit);
    });
}
 
Example #25
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 #26
Source File: MySQL8Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getWriteLockString(int timeout) {
	if ( timeout == LockOptions.NO_WAIT ) {
		return getForUpdateNowaitString();
	}
	else if ( timeout == LockOptions.SKIP_LOCKED ) {
		return getForUpdateSkipLockedString();
	}
	return super.getWriteLockString( timeout );
}
 
Example #27
Source File: ReactivePaddedBatchingEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ReactivePaddedBatchingEntityLoader(
		OuterJoinLoadable persister,
		int maxBatchSize,
		LockOptions lockOptions,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) {
	super( persister );
	this.batchSizes = ArrayHelper.getBatchSizes( maxBatchSize );
	this.loaders = new ReactiveEntityLoader[ batchSizes.length ];
	for ( int i = 0; i < batchSizes.length; i++ ) {
		this.loaders[i] = new ReactiveEntityLoader( persister, batchSizes[i], lockOptions, factory, loadQueryInfluencers);
	}
	validate( maxBatchSize );
}
 
Example #28
Source File: BatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds a batch-fetch capable loader based on the given persister, lock-options, etc.
 *
 * @param persister The entity persister
 * @param batchSize The maximum number of ids to batch-fetch at once
 * @param lockOptions The lock options
 * @param factory The SessionFactory
 * @param influencers Any influencers that should affect the built query
 *
 * @return The loader.
 */
public UniqueEntityLoader buildLoader(
		OuterJoinLoadable persister,
		int batchSize,
		LockOptions lockOptions,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	if ( batchSize <= 1 ) {
		// no batching
		return buildNonBatchingLoader( persister, lockOptions, factory, influencers );
	}
	return buildBatchingLoader( persister, batchSize, lockOptions, factory, influencers );
}
 
Example #29
Source File: ReactiveBatchingEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public CompletionStage<Object> load(
		Serializable id,
		Object optionalObject,
		SharedSessionContractImplementor session,
		LockOptions lockOptions,
		Boolean readOnly) {
	return load( id, optionalObject, session, lockOptions, readOnly );
}
 
Example #30
Source File: LegacyBatchingEntityLoaderBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public LegacyBatchingEntityLoader(
		OuterJoinLoadable persister,
		int maxBatchSize,
		LockOptions lockOptions,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) {
	super( persister );
	this.batchSizes = ArrayHelper.getBatchSizes( maxBatchSize );
	this.loaders = new Loader[ batchSizes.length ];
	for ( int i = 0; i < batchSizes.length; i++ ) {
		this.loaders[i] = new EntityLoader( persister, batchSizes[i], lockOptions, factory, loadQueryInfluencers);
	}
}