Search in sources :

Example 11 with LockMode

use of org.hibernate.LockMode in project hibernate-orm by hibernate.

the class DefaultPostLoadEventListener method onPostLoad.

@Override
public void onPostLoad(PostLoadEvent event) {
    final Object entity = event.getEntity();
    callbackRegistry.postLoad(entity);
    final EntityEntry entry = event.getSession().getPersistenceContext().getEntry(entity);
    if (entry == null) {
        throw new AssertionFailure("possible non-threadsafe access to the session");
    }
    final LockMode lockMode = entry.getLockMode();
    if (LockMode.PESSIMISTIC_FORCE_INCREMENT.equals(lockMode)) {
        final EntityPersister persister = entry.getPersister();
        final Object nextVersion = persister.forceVersionIncrement(entry.getId(), entry.getVersion(), event.getSession());
        entry.forceLocked(entity, nextVersion);
    } else if (LockMode.OPTIMISTIC_FORCE_INCREMENT.equals(lockMode)) {
        final EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess(entity, entry);
        event.getSession().getActionQueue().registerProcess(incrementVersion);
    } else if (LockMode.OPTIMISTIC.equals(lockMode)) {
        final EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess(entity, entry);
        event.getSession().getActionQueue().registerProcess(verifyVersion);
    }
    if (event.getPersister().implementsLifecycle()) {
        // log.debug( "calling onLoad()" );
        ((Lifecycle) event.getEntity()).onLoad(event.getSession(), event.getId());
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityEntry(org.hibernate.engine.spi.EntityEntry) AssertionFailure(org.hibernate.AssertionFailure) EntityVerifyVersionProcess(org.hibernate.action.internal.EntityVerifyVersionProcess) Lifecycle(org.hibernate.classic.Lifecycle) LockMode(org.hibernate.LockMode) EntityIncrementVersionProcess(org.hibernate.action.internal.EntityIncrementVersionProcess)

Example 12 with LockMode

use of org.hibernate.LockMode in project hibernate-orm by hibernate.

the class LoadPlanStructureAssertionHelper method performBasicComparison.

/**
 * Performs a basic comparison.  Builds a LoadPlan for the given persister and compares it against the
 * expectations according to the Loader/Walker corollary.
 *
 * @param sf The SessionFactory
 * @param persister The entity persister for which to build a LoadPlan and compare against the Loader/Walker
 * expectations.
 */
public void performBasicComparison(SessionFactoryImplementor sf, OuterJoinLoadable persister) {
    // todo : allow these to be passed in by tests?
    final LoadQueryInfluencers influencers = LoadQueryInfluencers.NONE;
    final LockMode lockMode = LockMode.NONE;
    final int batchSize = 1;
    // legacy Loader-based contracts...
    final EntityJoinWalker walker = new EntityJoinWalker(persister, persister.getKeyColumnNames(), batchSize, lockMode, sf, influencers);
    // final EntityLoader loader = new EntityLoader( persister, lockMode, sf, influencers );
    LoadPlan plan = buildLoadPlan(sf, persister, influencers, lockMode);
    LoadQueryDetails details = BatchingLoadQueryDetailsFactory.INSTANCE.makeEntityLoadQueryDetails(plan, persister.getKeyColumnNames(), new QueryBuildingParametersImpl(influencers, batchSize, lockMode, null), sf);
    compare(walker, details);
}
Also used : LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) QueryBuildingParametersImpl(org.hibernate.loader.plan.exec.query.internal.QueryBuildingParametersImpl) LoadPlan(org.hibernate.loader.plan.spi.LoadPlan) LoadQueryDetails(org.hibernate.loader.plan.exec.spi.LoadQueryDetails) EntityJoinWalker(org.hibernate.loader.entity.EntityJoinWalker) LockMode(org.hibernate.LockMode)

Example 13 with LockMode

use of org.hibernate.LockMode in project hibernate-orm by hibernate.

the class ParentChildTest method testComplexCriteria.

@Test
@SkipForDialect(value = H2Dialect.class, comment = "Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN")
public void testComplexCriteria() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Baz baz = new Baz();
    s.save(baz);
    baz.setDefaults();
    Map topGlarchez = new HashMap();
    baz.setTopGlarchez(topGlarchez);
    Glarch g1 = new Glarch();
    g1.setName("g1");
    s.save(g1);
    Glarch g2 = new Glarch();
    g2.setName("g2");
    s.save(g2);
    g1.setProxyArray(new GlarchProxy[] { g2 });
    topGlarchez.put(new Character('1'), g1);
    topGlarchez.put(new Character('2'), g2);
    Foo foo1 = new Foo();
    Foo foo2 = new Foo();
    s.save(foo1);
    s.save(foo2);
    baz.getFooSet().add(foo1);
    baz.getFooSet().add(foo2);
    baz.setFooArray(new FooProxy[] { foo1 });
    LockMode lockMode = supportsLockingNullableSideOfJoin(getDialect()) ? LockMode.UPGRADE : LockMode.READ;
    Criteria crit = s.createCriteria(Baz.class);
    crit.createCriteria("topGlarchez").add(Restrictions.isNotNull("name")).createCriteria("proxyArray").add(Restrictions.eqProperty("name", "name")).add(Restrictions.eq("name", "g2")).add(Restrictions.gt("x", new Integer(-666)));
    crit.createCriteria("fooSet").add(Restrictions.isNull("null")).add(Restrictions.eq("string", "a string")).add(Restrictions.lt("integer", new Integer(-665)));
    crit.createCriteria("fooArray").add(Restrictions.eq("string", "a string")).setLockMode(lockMode);
    List list = crit.list();
    assertTrue(list.size() == 2);
    s.createCriteria(Glarch.class).setLockMode(LockMode.UPGRADE).list();
    s.createCriteria(Glarch.class).setLockMode(Criteria.ROOT_ALIAS, LockMode.UPGRADE).list();
    g2.setName(null);
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    list = s.createCriteria(Baz.class).add(Restrictions.isEmpty("fooSet")).list();
    assertEquals(list.size(), 0);
    list = s.createCriteria(Baz.class).add(Restrictions.isNotEmpty("fooSet")).list();
    assertEquals(new HashSet(list).size(), 1);
    list = s.createCriteria(Baz.class).add(Restrictions.sizeEq("fooSet", 2)).list();
    assertEquals(new HashSet(list).size(), 1);
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    crit = s.createCriteria(Baz.class).setLockMode(lockMode);
    crit.createCriteria("topGlarchez").add(Restrictions.gt("x", new Integer(-666)));
    crit.createCriteria("fooSet").add(Restrictions.isNull("null"));
    list = crit.list();
    assertTrue(list.size() == 4);
    baz = (Baz) crit.uniqueResult();
    // cos it is nonlazy
    assertTrue(Hibernate.isInitialized(baz.getTopGlarchez()));
    assertTrue(!Hibernate.isInitialized(baz.getFooSet()));
    list = s.createCriteria(Baz.class).createCriteria("fooSet").createCriteria("foo").createCriteria("component.glarch").add(Restrictions.eq("name", "xxx")).list();
    assertTrue(list.size() == 0);
    list = s.createCriteria(Baz.class).createAlias("fooSet", "foo").createAlias("foo.foo", "foo2").setLockMode("foo2", lockMode).add(Restrictions.isNull("foo2.component.glarch")).createCriteria("foo2.component.glarch").add(Restrictions.eq("name", "xxx")).list();
    assertTrue(list.size() == 0);
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    crit = s.createCriteria(Baz.class);
    crit.createCriteria("topGlarchez").add(Restrictions.isNotNull("name"));
    crit.createCriteria("fooSet").add(Restrictions.isNull("null"));
    list = crit.list();
    assertTrue(list.size() == 2);
    baz = (Baz) crit.uniqueResult();
    // cos it is nonlazy
    assertTrue(Hibernate.isInitialized(baz.getTopGlarchez()));
    assertTrue(!Hibernate.isInitialized(baz.getFooSet()));
    s.createCriteria(Child.class).setFetchMode("parent", FetchMode.JOIN).list();
    doDelete(s, "from Glarch g");
    s.delete(s.get(Foo.class, foo1.getKey()));
    s.delete(s.get(Foo.class, foo2.getKey()));
    s.delete(baz);
    t.commit();
    s.close();
}
Also used : HashMap(java.util.HashMap) LockMode(org.hibernate.LockMode) Criteria(org.hibernate.Criteria) Transaction(org.hibernate.Transaction) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Session(org.hibernate.Session) HashSet(java.util.HashSet) SkipForDialect(org.hibernate.testing.SkipForDialect) Test(org.junit.Test)

Example 14 with LockMode

use of org.hibernate.LockMode in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method getQueryParameters.

public QueryParameters getQueryParameters() {
    final RowSelection selection = new RowSelection();
    selection.setFirstRow(rootCriteria.getFirstResult());
    selection.setMaxRows(rootCriteria.getMaxResults());
    selection.setTimeout(rootCriteria.getTimeout());
    selection.setFetchSize(rootCriteria.getFetchSize());
    final LockOptions lockOptions = new LockOptions();
    final Map<String, LockMode> lockModeMap = rootCriteria.getLockModes();
    for (final String key : lockModeMap.keySet()) {
        final Criteria subcriteria = getAliasedCriteria(key);
        lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lockModeMap.get(key));
    }
    final List<Object> values = new ArrayList<Object>();
    final List<Type> types = new ArrayList<Type>();
    final Iterator<CriteriaImpl.Subcriteria> subcriteriaIterator = rootCriteria.iterateSubcriteria();
    while (subcriteriaIterator.hasNext()) {
        final CriteriaImpl.Subcriteria subcriteria = subcriteriaIterator.next();
        final LockMode lm = subcriteria.getLockMode();
        if (lm != null) {
            lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lm);
        }
        if (subcriteria.getWithClause() != null) {
            final TypedValue[] tv = subcriteria.getWithClause().getTypedValues(subcriteria, this);
            for (TypedValue aTv : tv) {
                values.add(aTv.getValue());
                types.add(aTv.getType());
            }
        }
    }
    // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering,
    // because the lock mode gathering loop now contains join clauses which can contain
    // parameter bindings (as in the HQL WITH clause).
    final Iterator<CriteriaImpl.CriterionEntry> iter = rootCriteria.iterateExpressionEntries();
    while (iter.hasNext()) {
        final CriteriaImpl.CriterionEntry ce = iter.next();
        final TypedValue[] tv = ce.getCriterion().getTypedValues(ce.getCriteria(), this);
        for (TypedValue aTv : tv) {
            values.add(aTv.getValue());
            types.add(aTv.getType());
        }
    }
    final Object[] valueArray = values.toArray();
    final Type[] typeArray = ArrayHelper.toTypeArray(types);
    return new QueryParameters(typeArray, valueArray, lockOptions, selection, rootCriteria.isReadOnlyInitialized(), (rootCriteria.isReadOnlyInitialized() && rootCriteria.isReadOnly()), rootCriteria.getCacheable(), rootCriteria.getCacheRegion(), rootCriteria.getComment(), rootCriteria.getQueryHints(), rootCriteria.isLookupByNaturalKey(), rootCriteria.getResultTransformer());
}
Also used : LockOptions(org.hibernate.LockOptions) CriteriaImpl(org.hibernate.internal.CriteriaImpl) ArrayList(java.util.ArrayList) LockMode(org.hibernate.LockMode) Criteria(org.hibernate.Criteria) QueryParameters(org.hibernate.engine.spi.QueryParameters) RowSelection(org.hibernate.engine.spi.RowSelection) StringRepresentableType(org.hibernate.type.StringRepresentableType) CollectionType(org.hibernate.type.CollectionType) JoinType(org.hibernate.sql.JoinType) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) TypedValue(org.hibernate.engine.spi.TypedValue)

Example 15 with LockMode

use of org.hibernate.LockMode in project hibernate-orm by hibernate.

the class CriteriaLoader method applyLocks.

@Override
protected String applyLocks(String sql, QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) throws QueryException {
    final LockOptions lockOptions = parameters.getLockOptions();
    if (lockOptions == null || (lockOptions.getLockMode() == LockMode.NONE && (lockOptions.getAliasLockCount() == 0 || (lockOptions.getAliasLockCount() == 1 && lockOptions.getAliasSpecificLockMode("this_") == LockMode.NONE)))) {
        return sql;
    }
    if ((parameters.getLockOptions().getFollowOnLocking() == null && dialect.useFollowOnLocking(parameters)) || (parameters.getLockOptions().getFollowOnLocking() != null && parameters.getLockOptions().getFollowOnLocking())) {
        final LockMode lockMode = determineFollowOnLockMode(lockOptions);
        if (lockMode != LockMode.UPGRADE_SKIPLOCKED) {
            // Dialect prefers to perform locking in a separate step
            LOG.usingFollowOnLocking();
            final LockOptions lockOptionsToUse = new LockOptions(lockMode);
            lockOptionsToUse.setTimeOut(lockOptions.getTimeOut());
            lockOptionsToUse.setScope(lockOptions.getScope());
            afterLoadActions.add(new AfterLoadAction() {

                @Override
                public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
                    ((Session) session).buildLockRequest(lockOptionsToUse).lock(persister.getEntityName(), entity);
                }
            });
            parameters.setLockOptions(new LockOptions());
            return sql;
        }
    }
    final LockOptions locks = new LockOptions(lockOptions.getLockMode());
    locks.setScope(lockOptions.getScope());
    locks.setTimeOut(lockOptions.getTimeOut());
    final Map<String, String[]> keyColumnNames = dialect.forUpdateOfColumns() ? new HashMap() : null;
    final String[] drivingSqlAliases = getAliases();
    for (int i = 0; i < drivingSqlAliases.length; i++) {
        final LockMode lockMode = lockOptions.getAliasSpecificLockMode(drivingSqlAliases[i]);
        if (lockMode != null) {
            final Lockable drivingPersister = (Lockable) getEntityPersisters()[i];
            final String rootSqlAlias = drivingPersister.getRootTableAlias(drivingSqlAliases[i]);
            locks.setAliasSpecificLockMode(rootSqlAlias, lockMode);
            if (keyColumnNames != null) {
                keyColumnNames.put(rootSqlAlias, drivingPersister.getRootTableIdentifierColumnNames());
            }
        }
    }
    return dialect.applyLocksToSql(sql, locks, keyColumnNames);
}
Also used : OuterJoinLoadable(org.hibernate.persister.entity.OuterJoinLoadable) Loadable(org.hibernate.persister.entity.Loadable) LockOptions(org.hibernate.LockOptions) HashMap(java.util.HashMap) AfterLoadAction(org.hibernate.loader.spi.AfterLoadAction) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) LockMode(org.hibernate.LockMode) Lockable(org.hibernate.persister.entity.Lockable) Session(org.hibernate.Session)

Aggregations

LockMode (org.hibernate.LockMode)25 Map (java.util.Map)9 HashMap (java.util.HashMap)8 LockOptions (org.hibernate.LockOptions)4 EntityPath (com.querydsl.core.types.EntityPath)3 Path (com.querydsl.core.types.Path)3 JPQLSerializer (com.querydsl.jpa.JPQLSerializer)3 ArrayList (java.util.ArrayList)3 LinkedHashMap (java.util.LinkedHashMap)3 Session (org.hibernate.Session)3 Query (org.hibernate.query.Query)3 Iterator (java.util.Iterator)2 List (java.util.List)2 Criteria (org.hibernate.Criteria)2 EntityDataAccess (org.hibernate.cache.spi.access.EntityDataAccess)2 EntityKey (org.hibernate.engine.spi.EntityKey)2 LoadQueryInfluencers (org.hibernate.engine.spi.LoadQueryInfluencers)2 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)2 EntityJoinWalker (org.hibernate.loader.entity.EntityJoinWalker)2 LoadQueryDetails (org.hibernate.loader.plan.exec.spi.LoadQueryDetails)2