Example usage for org.hibernate LockOptions getLockMode

List of usage examples for org.hibernate LockOptions getLockMode

Introduction

In this page you can find the example usage for org.hibernate LockOptions getLockMode.

Prototype

public LockMode getLockMode() 

Source Link

Document

Retrieve the overall lock mode in effect for this set of options.

Usage

From source file:com.blazebit.persistence.integration.hibernate.base.HibernateExtendedQuerySupport.java

License:Apache License

private QueryParamEntry createQueryParameters(EntityManager em, List<Query> participatingQueries,
        List<String> queryStrings, Set<String> querySpaces) {
    List<ParameterSpecification> parameterSpecifications = new ArrayList<ParameterSpecification>();

    List<Type> types = new ArrayList<Type>();
    List<Object> values = new ArrayList<Object>();
    Map<String, TypedValue> namedParams = new LinkedHashMap<String, TypedValue>();
    Serializable collectionKey = null;
    LockOptions lockOptions = new LockOptions();
    RowSelection rowSelection = new RowSelection();
    boolean readOnly = false; // TODO: readonly?
    boolean cacheable = false; // TODO: cacheable?
    String cacheRegion = null;//w  w  w.  ja  v a2s. c  o  m
    String comment = null;
    List<String> queryHints = null;

    for (QueryParamEntry queryParamEntry : getQueryParamEntries(em, participatingQueries, querySpaces)) {
        queryStrings.add(queryParamEntry.queryString);

        QueryParameters participatingQueryParameters = queryParamEntry.queryParameters;
        // Merge parameters
        Collections.addAll(types, participatingQueryParameters.getPositionalParameterTypes());
        Collections.addAll(values, participatingQueryParameters.getPositionalParameterValues());
        namedParams.putAll(participatingQueryParameters.getNamedParameters());
        parameterSpecifications.addAll(queryParamEntry.specifications);

        // Merge row selections
        if (participatingQueryParameters.hasRowSelection()) {
            RowSelection original = queryParamEntry.queryParameters.getRowSelection();
            // Check for defaults

            /***************************************************************************
             * TODO: Either we do it like this, or let these values be passed in separately
             **************************************************************************/

            if (rowSelection.getFirstRow() == null || rowSelection.getFirstRow() < 1) {
                rowSelection.setFirstRow(original.getFirstRow());
            } else if (original.getFirstRow() != null && original.getFirstRow() > 0
                    && !original.getFirstRow().equals(rowSelection.getFirstRow())) {
                throw new IllegalStateException("Multiple row selections not allowed!");
            }
            if (rowSelection.getMaxRows() == null || rowSelection.getMaxRows() == Integer.MAX_VALUE) {
                rowSelection.setMaxRows(original.getMaxRows());
            } else if (original.getMaxRows() != null && original.getMaxRows() != Integer.MAX_VALUE
                    && !original.getMaxRows().equals(rowSelection.getMaxRows())) {
                throw new IllegalStateException("Multiple row selections not allowed!");
            }

            if (rowSelection.getFetchSize() == null) {
                rowSelection.setFetchSize(original.getFetchSize());
            } else if (original.getFetchSize() != null
                    && !original.getFetchSize().equals(rowSelection.getFetchSize())) {
                throw new IllegalStateException("Multiple row selections not allowed!");
            }
            if (rowSelection.getTimeout() == null) {
                rowSelection.setTimeout(original.getTimeout());
            } else if (original.getTimeout() != null
                    && !original.getTimeout().equals(rowSelection.getTimeout())) {
                throw new IllegalStateException("Multiple row selections not allowed!");
            }
        }

        // Merge lock options
        LockOptions originalLockOptions = participatingQueryParameters.getLockOptions();
        if (originalLockOptions.getScope()) {
            lockOptions.setScope(true);
        }
        if (originalLockOptions.getLockMode() != LockMode.NONE) {
            if (lockOptions.getLockMode() != LockMode.NONE
                    && lockOptions.getLockMode() != originalLockOptions.getLockMode()) {
                throw new IllegalStateException("Multiple different lock modes!");
            }
            lockOptions.setLockMode(originalLockOptions.getLockMode());
        }
        if (originalLockOptions.getTimeOut() != -1) {
            if (lockOptions.getTimeOut() != -1
                    && lockOptions.getTimeOut() != originalLockOptions.getTimeOut()) {
                throw new IllegalStateException("Multiple different lock timeouts!");
            }
            lockOptions.setTimeOut(originalLockOptions.getTimeOut());
        }
        @SuppressWarnings("unchecked")
        Iterator<Map.Entry<String, LockMode>> aliasLockIter = participatingQueryParameters.getLockOptions()
                .getAliasLockIterator();
        while (aliasLockIter.hasNext()) {
            Map.Entry<String, LockMode> entry = aliasLockIter.next();
            lockOptions.setAliasSpecificLockMode(entry.getKey(), entry.getValue());
        }
    }

    QueryParameters queryParameters = hibernateAccess.createQueryParameters(
            types.toArray(new Type[types.size()]), values.toArray(new Object[values.size()]), namedParams,
            lockOptions, rowSelection, true, readOnly, cacheable, cacheRegion, comment, queryHints,
            collectionKey == null ? null : new Serializable[] { collectionKey });

    return new QueryParamEntry(null, queryParameters, parameterSpecifications);
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java

License:Apache License

public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate,
        OperationResult operationResult)
        throws ObjectNotFoundException, SchemaException, DtoTranslationException {

    boolean lockedForUpdateViaHibernate = false;
    boolean lockedForUpdateViaSql = false;

    LockOptions lockOptions = new LockOptions();
    //todo fix lock for update!!!!!
    if (lockForUpdate) {
        if (getConfiguration().isLockForUpdateViaHibernate()) {
            lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
            lockedForUpdateViaHibernate = true;
        } else if (getConfiguration().isLockForUpdateViaSql()) {
            LOGGER.trace("Trying to lock object {} for update (via SQL)", oid);
            long time = System.currentTimeMillis();
            SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update");
            q.setString(0, oid);//from w  w w  .  j av a 2s  .  c  om
            Object result = q.uniqueResult();
            if (result == null) {
                return throwObjectNotFoundException(type, oid);
            }
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time);
            }
            lockedForUpdateViaSql = true;
        }
    }

    if (LOGGER.isTraceEnabled()) {
        if (lockedForUpdateViaHibernate) {
            LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid);
        } else if (lockedForUpdateViaSql) {
            LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid);
        } else {
            LOGGER.trace("Getting object {} without locking for update", oid);
        }
    }

    GetObjectResult fullObject = null;
    if (!lockForUpdate) {
        Query query = session.getNamedQuery("get.object");
        query.setString("oid", oid);
        query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
        query.setLockOptions(lockOptions);

        fullObject = (GetObjectResult) query.uniqueResult();
    } else {
        // we're doing update after this get, therefore we load full object right now
        // (it would be loaded during merge anyway)
        // this just loads object to hibernate session, probably will be removed later. Merge after this get
        // will be faster. Read and use object only from fullObject column.
        // todo remove this later [lazyman]
        Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type));
        criteria.add(Restrictions.eq("oid", oid));

        criteria.setLockMode(lockOptions.getLockMode());
        RObject obj = (RObject) criteria.uniqueResult();

        if (obj != null) {
            obj.toJAXB(prismContext, null).asPrismObject();
            fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(),
                    obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(), obj.getBooleansCount());
        }
    }

    LOGGER.trace("Got it.");
    if (fullObject == null) {
        throwObjectNotFoundException(type, oid);
    }

    LOGGER.trace("Transforming data to JAXB type.");
    PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, session, operationResult);
    validateObjectType(prismObject, type);

    // this was implemented to allow report parsing errors as warnings to upper layers;
    // however, it causes problems when serialization problems are encountered: in such cases, we put
    // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication)
    // -- so, as the parsing errors are not implemented, we disabled this code as well

    //         subResult.computeStatusIfUnknown();
    //         if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) {
    //            prismObject.asObjectable().setFetchResult(subResult.createOperationResultType());
    //         }

    return prismObject;
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private <T extends ObjectType> PrismObject<T> getObject(Session session, Class<T> type, String oid,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate)
        throws ObjectNotFoundException, SchemaException, DtoTranslationException, QueryException {

    boolean lockedForUpdateViaHibernate = false;
    boolean lockedForUpdateViaSql = false;

    LockOptions lockOptions = new LockOptions();
    //todo fix lock for update!!!!!
    if (lockForUpdate) {
        if (getConfiguration().isLockForUpdateViaHibernate()) {
            lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
            lockedForUpdateViaHibernate = true;
        } else if (getConfiguration().isLockForUpdateViaSql()) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Trying to lock object " + oid + " for update (via SQL)");
            }/*from ww w.j av  a2s. c  o  m*/
            long time = System.currentTimeMillis();
            SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update");
            q.setString(0, oid);
            Object result = q.uniqueResult();
            if (result == null) {
                return throwObjectNotFoundException(type, oid);
            }
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Locked via SQL (in " + (System.currentTimeMillis() - time) + " ms)");
            }
            lockedForUpdateViaSql = true;
        }
    }

    if (LOGGER.isTraceEnabled()) {
        if (lockedForUpdateViaHibernate) {
            LOGGER.trace("Getting object " + oid + " with locking for update (via hibernate)");
        } else if (lockedForUpdateViaSql) {
            LOGGER.trace("Getting object " + oid + ", already locked for update (via SQL)");
        } else {
            LOGGER.trace("Getting object " + oid + " without locking for update");
        }
    }

    GetObjectResult fullObject = null;
    if (!lockForUpdate) {
        Query query = session.getNamedQuery("get.object");
        query.setString("oid", oid);
        query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
        query.setLockOptions(lockOptions);

        fullObject = (GetObjectResult) query.uniqueResult();
    } else {
        // we're doing update after this get, therefore we load full object right now
        // (it would be loaded during merge anyway)
        // this just loads object to hibernate session, probably will be removed later. Merge after this get
        // will be faster. Read and use object only from fullObject column.
        // todo remove this later [lazyman]
        Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type));
        criteria.add(Restrictions.eq("oid", oid));

        criteria.setLockMode(lockOptions.getLockMode());
        RObject obj = (RObject) criteria.uniqueResult();

        if (obj != null) {
            obj.toJAXB(getPrismContext(), null).asPrismObject();
            fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(),
                    obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount());
        }
    }

    LOGGER.trace("Got it.");
    if (fullObject == null) {
        throwObjectNotFoundException(type, oid);
    }

    LOGGER.trace("Transforming data to JAXB type.");
    PrismObject<T> prismObject = updateLoadedObject(fullObject, type, options, session);
    validateObjectType(prismObject, type);

    return prismObject;
}