Example usage for org.hibernate Criteria setLockMode

List of usage examples for org.hibernate Criteria setLockMode

Introduction

In this page you can find the example usage for org.hibernate Criteria setLockMode.

Prototype

public Criteria setLockMode(LockMode lockMode);

Source Link

Document

Set the lock mode of the current entity.

Usage

From source file:com.amalto.core.storage.hibernate.LockUpdateSession.java

License:Open Source License

@Override
public Criteria createCriteria(Class persistentClass) {
    Criteria criteria = delegate.createCriteria(persistentClass);
    criteria.setLockMode(mode);
    return criteria;
}

From source file:com.amalto.core.storage.hibernate.LockUpdateSession.java

License:Open Source License

@Override
public Criteria createCriteria(Class persistentClass, String alias) {
    Criteria criteria = delegate.createCriteria(persistentClass, alias);
    criteria.setLockMode(mode);
    return criteria;
}

From source file:com.amalto.core.storage.hibernate.LockUpdateSession.java

License:Open Source License

@Override
public Criteria createCriteria(String entityName) {
    Criteria criteria = delegate.createCriteria(entityName);
    criteria.setLockMode(mode);
    return criteria;
}

From source file:com.amalto.core.storage.hibernate.LockUpdateSession.java

License:Open Source License

@Override
public Criteria createCriteria(String entityName, String alias) {
    Criteria criteria = delegate.createCriteria(entityName, alias);
    criteria.setLockMode(mode);
    return criteria;
}

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);/*ww  w  . jav  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  .ja  v a 2  s . c om
            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;
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./*from   w  w  w .j  a  v a2s  . c  om*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.openjmsadapter.configuration.database.DatabaseConfigHolder.java

License:Open Source License

public boolean persistConfiguration() throws Exception {
    sessionFactory.getCurrentSession().beginTransaction();
    for (DestinationConfiguration dest_config : config.getDestinations()) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(JmsDestinationParameters.class);
        criteria.setLockMode(LockMode.UPGRADE);
        criteria.add(Restrictions.like("destinationName", dest_config.getDestinantionName()));
        JmsDestinationParameters param = (JmsDestinationParameters) criteria.uniqueResult();
        param.setLastSequenceReceived(dest_config.getLastSequenceReceived());
        param.setLastSequenceSent(dest_config.getLastSequenceSent());
        sessionFactory.getCurrentSession().save(param);
    }/*from   w w  w . j a v a 2  s. com*/
    sessionFactory.getCurrentSession().getTransaction().commit();
    sessionFactory.getCurrentSession().close();
    sessionFactory.close();
    return true;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param grailsApplication the GrailsApplication instance
 * @param targetClass The target class//from  w  w  w  . j a v a2 s. c o m
 * @param c The criteria instance
 * @param argMap The arguments map
 *
        
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(GrailsApplication grailsApplication, Class<?> targetClass,
        Criteria c, Map argMap) {
    Integer maxParam = null;
    Integer offsetParam = null;
    SimpleTypeConverter converter = new SimpleTypeConverter();
    if (argMap.containsKey(ARGUMENT_MAX)) {
        maxParam = converter.convertIfNecessary(argMap.get(ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_OFFSET)) {
        offsetParam = converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) {
        c.setFetchSize(converter.convertIfNecessary(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_TIMEOUT)) {
        c.setTimeout(converter.convertIfNecessary(argMap.get(ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) {
        c.setFlushMode(converter.convertIfNecessary(argMap.get(ARGUMENT_FLUSH_MODE), FlushMode.class));
    }
    if (argMap.containsKey(ARGUMENT_READ_ONLY)) {
        c.setReadOnly(GrailsClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap));
    }
    String orderParam = (String) argMap.get(ARGUMENT_ORDER);
    Object fetchObj = argMap.get(ARGUMENT_FETCH);
    if (fetchObj instanceof Map) {
        Map fetch = (Map) fetchObj;
        for (Object o : fetch.keySet()) {
            String associationName = (String) o;
            c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
        }
    }

    final String sort = (String) argMap.get(ARGUMENT_SORT);
    final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        c.setMaxResults(max);
    }
    if (offset > -1) {
        c.setFirstResult(offset);
    }
    if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)) {
        c.setCacheable(true);
    }
    if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) {
        c.setLockMode(LockMode.PESSIMISTIC_WRITE);
    } else {
        if (argMap.get(ARGUMENT_CACHE) == null) {
            cacheCriteriaByMapping(targetClass, c);
        }
    }
    if (sort != null) {
        boolean ignoreCase = true;
        Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
        if (caseArg instanceof Boolean) {
            ignoreCase = (Boolean) caseArg;
        }
        addOrderPossiblyNested(grailsApplication, c, targetClass, sort, order, ignoreCase);
    } else {
        Mapping m = GrailsDomainBinder.getMapping(targetClass);
        if (m != null && !StringUtils.isBlank(m.getSort())) {
            addOrderPossiblyNested(grailsApplication, c, targetClass, m.getSort(), m.getOrder(), true);
        }
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param datastore the GrailsApplication instance
 * @param targetClass The target class/*from   w  ww .  j  ava 2s. c o  m*/
 * @param c The criteria instance
 * @param argMap The arguments map
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(AbstractHibernateDatastore datastore, Class<?> targetClass,
        Criteria c, Map argMap, ConversionService conversionService, boolean useDefaultMapping) {
    Integer maxParam = null;
    Integer offsetParam = null;
    if (argMap.containsKey(ARGUMENT_MAX)) {
        maxParam = conversionService.convert(argMap.get(ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_OFFSET)) {
        offsetParam = conversionService.convert(argMap.get(ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) {
        c.setFetchSize(conversionService.convert(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_TIMEOUT)) {
        c.setTimeout(conversionService.convert(argMap.get(ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) {
        c.setFlushMode(convertFlushMode(argMap.get(ARGUMENT_FLUSH_MODE)));
    }
    if (argMap.containsKey(ARGUMENT_READ_ONLY)) {
        c.setReadOnly(ClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap));
    }
    String orderParam = (String) argMap.get(ARGUMENT_ORDER);
    Object fetchObj = argMap.get(ARGUMENT_FETCH);
    if (fetchObj instanceof Map) {
        Map fetch = (Map) fetchObj;
        for (Object o : fetch.keySet()) {
            String associationName = (String) o;
            c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
        }
    }

    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        c.setMaxResults(max);
    }
    if (offset > -1) {
        c.setFirstResult(offset);
    }
    if (ClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) {
        c.setLockMode(LockMode.PESSIMISTIC_WRITE);
        c.setCacheable(false);
    } else {
        if (argMap.containsKey(ARGUMENT_CACHE)) {
            c.setCacheable(ClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap));
        } else {
            cacheCriteriaByMapping(targetClass, c);
        }
    }

    final Object sortObj = argMap.get(ARGUMENT_SORT);
    if (sortObj != null) {
        boolean ignoreCase = true;
        Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
        if (caseArg instanceof Boolean) {
            ignoreCase = (Boolean) caseArg;
        }
        if (sortObj instanceof Map) {
            Map sortMap = (Map) sortObj;
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, ignoreCase);
            }
        } else {
            final String sort = (String) sortObj;
            final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
            addOrderPossiblyNested(datastore, c, targetClass, sort, order, ignoreCase);
        }
    } else if (useDefaultMapping) {
        Mapping m = GrailsDomainBinder.getMapping(targetClass);
        if (m != null) {
            Map sortMap = m.getSort().getNamesAndDirections();
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, true);
            }
        }
    }
}