Example usage for org.hibernate LockMode WRITE

List of usage examples for org.hibernate LockMode WRITE

Introduction

In this page you can find the example usage for org.hibernate LockMode WRITE.

Prototype

LockMode WRITE

To view the source code for org.hibernate LockMode WRITE.

Click Source Link

Document

A WRITE lock is obtained when an object is updated or inserted.

Usage

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

License:Apache License

/**
 * Initializes a Criteria Query./*from   w w w .ja v a2 s.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:org.apache.camel.component.hibernate.HibernateConsumer.java

License:Apache License

/**
 * A strategy method to lock an object with an exclusive lock so that it can
 * be processed//from  w w  w  . ja v a  2 s .  co m
 *
 * @param entity  the entity to be locked
 * @param session
 * @return true if the entity was locked
 */
protected boolean lockEntity(Object entity, Session session) {
    if (!getEndpoint().isConsumeDelete() || !getEndpoint().isConsumeLockEntity()) {
        return true;
    }
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Acquiring exclusive lock on entity: " + entity);
        }
        session.lock(entity, LockMode.WRITE);
        return true;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e);
        }
        return false;
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.java

License:Apache License

@Override
protected Serializable performSaveOrReplicate(Object entity, EntityKey key, EntityPersister persister,
        boolean useIdentityColumn, Object anything, EventSource source, boolean requiresImmediateIdAccess) {
    validate(entity, persister, source);

    Serializable id = key == null ? null : key.getIdentifier();

    boolean inTxn = source.getJDBCContext().isTransactionInProgress();
    boolean shouldDelayIdentityInserts = !inTxn && !requiresImmediateIdAccess;

    // Put a placeholder in entries, so we don't recurse back and try to save() the
    // same object again. QUESTION: should this be done before onSave() is called?
    // likewise, should it be done before onUpdate()?
    source.getPersistenceContext().addEntry(entity, Status.SAVING, null, null, id, null, LockMode.WRITE,
            useIdentityColumn, persister, false, false);

    cascadeBeforeSave(source, persister, entity, anything);

    if (useIdentityColumn && !shouldDelayIdentityInserts) {
        log.trace("executing insertions");
        source.getActionQueue().executeInserts();
    }/* w  w  w  .  j  av a 2 s . c o  m*/

    Object[] values = persister.getPropertyValuesToInsert(entity, getMergeMap(anything), source);
    Type[] types = persister.getPropertyTypes();

    boolean substitute = substituteValuesIfNecessary(entity, id, values, persister, source);

    if (persister.hasCollections()) {
        substitute = substitute || visitCollectionsBeforeSave(entity, id, values, types, source);
    }

    if (substitute) {
        persister.setPropertyValues(entity, values, source.getEntityMode());
    }

    TypeHelper.deepCopy(values, types, persister.getPropertyUpdateability(), values, source);

    new ForeignKeys.Nullifier(entity, false, useIdentityColumn, source).nullifyTransientReferences(values,
            types);
    new Nullability(source).checkNullability(values, persister, false);

    if (useIdentityColumn) {
        EntityIdentityInsertAction insert = new EntityIdentityInsertAction(values, entity, persister, source,
                shouldDelayIdentityInserts);
        if (!shouldDelayIdentityInserts) {
            log.debug("executing identity-insert immediately");
            source.getActionQueue().execute(insert);
            id = insert.getGeneratedId();
            if (id != null) {
                // As of HHH-3904, if the id is null the operation was vetoed so we bail
                key = new EntityKey(id, persister, source.getEntityMode());
                source.getPersistenceContext().checkUniqueness(key, entity);
            }
        } else {
            log.debug("delaying identity-insert due to no transaction in progress");
            source.getActionQueue().addAction(insert);
            key = insert.getDelayedEntityKey();
        }
    }

    if (key != null) {
        Object version = Versioning.getVersion(values, persister);
        source.getPersistenceContext().addEntity(entity,
                (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY), values, key, version,
                LockMode.WRITE, useIdentityColumn, persister, isVersionIncrementDisabled(), false);
        //source.getPersistenceContext().removeNonExist(new EntityKey(id, persister, source.getEntityMode()));

        if (!useIdentityColumn) {
            source.getActionQueue()
                    .addAction(new EntityInsertAction(id, values, entity, version, persister, source));
        }

        cascadeAfterSave(source, persister, entity, anything);
        // Very unfortunate code, but markInterceptorDirty is private. Once HHH-3904 is resolved remove this overridden method!
        if (markInterceptorDirtyMethod != null) {
            ReflectionUtils.invokeMethod(markInterceptorDirtyMethod, this, entity, persister, source);
        }
    }

    return id;
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testLock() throws HibernateException {
    TestBean tb = new TestBean();
    hibernateTemplate.lock(tb, LockMode.WRITE);
    verify(session).lock(tb, LockMode.WRITE);
    verify(session).flush();//from w w w.  j av a2 s .com
    verify(session).close();
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@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();//  w ww .j a v  a 2 s  .c  om
    verify(session).close();
}