Example usage for org.hibernate Session buildLockRequest

List of usage examples for org.hibernate Session buildLockRequest

Introduction

In this page you can find the example usage for org.hibernate Session buildLockRequest.

Prototype

LockRequest buildLockRequest(LockOptions lockOptions);

Source Link

Document

Build a LockRequest that specifies the LockMode, pessimistic lock timeout and lock scope.

Usage

From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateBackendController.java

License:Open Source License

/**
 * Locks an entity (LockMode.NONE) in current hibernate session.
 *
 * @param entity/*  ww  w .j  a  v a 2 s. c  o m*/
 *     the entity to lock.
 * @param hibernateSession
 *     the hibernate session.
 */
private void lockInHibernate(IEntity entity, Session hibernateSession) {
    if (!hibernateSession.contains(entity)) {
        // Do not use get before trying to lock.
        // Get performs a DB query.
        try {
            hibernateSession.buildLockRequest(LockOptions.NONE).lock(entity);
        } catch (NonUniqueObjectException ex) {
            if (hibernateSession == noTxSession) {
                hibernateSession.clear();
                hibernateSession.buildLockRequest(LockOptions.NONE).lock(entity);
            } else {
                throw ex;
            }
        }
    }
}

From source file:org.molasdin.wbase.hibernate.BasicHibernateRepository.java

License:Apache License

private void attachRaw(T o, Session session) {
    if (session.contains(o)) {
        return;/*from ww w  .ja  va2 s .  c  om*/
    }
    session.buildLockRequest(LockOptions.NONE).lock(o);
}

From source file:org.molasdin.wbase.hibernate.cursor.BasicFilteredHibernateCursor.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  ww.j a v a  2 s  .co m*/
public List<T> dataCallback(Session session) {
    StringBuilder builder = new StringBuilder();
    session.buildLockRequest(LockOptions.NONE).lock(owner);
    builder.append(populateFilters());
    builder.append(' ');

    List<Pair<String, Order>> orders = orders();
    if (!orders.isEmpty()) {
        builder.append("order by ");
        boolean added = false;
        for (Pair<String, Order> order : orders) {
            if (added) {
                builder.append(",");
            }
            builder.append(String.format(FILTER_ORDER, order.getLeft(),
                    Order.ASC.equals(order.getRight()) ? ORDER_ASC : ORDER_DESC));
            added = true;
        }
        builder.append(' ');
    }

    return postProcessData((List<T>) session.createFilter(collectionProxy, builder.toString())
            .setFirstResult(calculatedRowOffset()).setMaxResults(pageSize()).list());
}

From source file:org.molasdin.wbase.hibernate.cursor.BasicFilteredHibernateCursor.java

License:Apache License

@Override
public Long totalCallback(Session session) {
    StringBuilder builder = new StringBuilder();
    builder.append("select count(*) ");
    builder.append(populateFilters());//from   w w w.ja v  a 2 s.  co m
    session.buildLockRequest(LockOptions.NONE).lock(owner);
    return (Long) session.createFilter(collectionProxy, builder.toString()).uniqueResult();
}

From source file:org.obiba.opal.core.upgrade.v2_0_x.database.FixAttributeJoinTableUpgradeStep.java

License:Open Source License

@SuppressWarnings("unchecked")
private void touchValueTablesTimestamps(final Database database) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override//from  ww  w . j a v a  2  s .c  om
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            SessionFactory sessionFactory = databaseRegistry.getSessionFactory(database.getName(), null);
            Session currentSession = sessionFactory.getCurrentSession();
            for (ValueTableState table : (List<ValueTableState>) currentSession
                    .createCriteria(ValueTableState.class).list()) {
                log.debug("Touch {} last update", table.getName());
                currentSession.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_FORCE_INCREMENT))
                        .lock(table);
            }
        }
    });
}

From source file:org.openmrs.cwf.api.util.OpenMRSUtil.java

License:Mozilla Public License

public static void loadIfNecessary(Object domainObject) {
    Session session = null;

    try {//  w  w w  . j  a  v a  2 s.c o m
        session = getSessionFactory().getCurrentSession();

        if (!session.contains(domainObject)) {
            LockRequest lr = session.buildLockRequest(LockOptions.NONE);
            lr.lock(domainObject);
        }
    } catch (org.hibernate.NonUniqueObjectException exc) {
        session.merge(domainObject);
    } catch (org.hibernate.LazyInitializationException exc) {
        session.merge(domainObject);
    }
}

From source file:org.sakaiproject.assignment.impl.persistence.AssignmentRepositoryImpl.java

License:Educational Community License

@Override
@Transactional/*from  w ww . jav a 2s. c  o  m*/
public AssignmentSubmission newSubmission(String assignmentId, Optional<String> groupId,
        Optional<Set<AssignmentSubmissionSubmitter>> submitters, Optional<Set<String>> feedbackAttachments,
        Optional<Set<String>> submittedAttachments, Optional<Map<String, String>> properties) {
    Assignment assignment = findAssignment(assignmentId);
    if (assignment != null) {
        Session session = sessionFactory.getCurrentSession();
        // Since this transaction is going to add a submission to the assignment we lock the assignment
        // the lock is freed once transaction is committed or rolled back
        session.buildLockRequest(LockOptions.UPGRADE).setLockMode(LockMode.PESSIMISTIC_WRITE).lock(assignment);

        AssignmentSubmission submission = new AssignmentSubmission();
        submission.setDateCreated(Instant.now());
        submitters.ifPresent(submission::setSubmitters);
        submitters.ifPresent(s -> s.forEach(submitter -> submitter.setSubmission(submission)));
        feedbackAttachments.ifPresent(submission::setFeedbackAttachments);
        submittedAttachments.ifPresent(submission::setAttachments);
        properties.ifPresent(submission::setProperties);
        if (assignment.getIsGroup()) {
            groupId.ifPresent(submission::setGroupId);
        }

        submission.setAssignment(assignment);
        assignment.getSubmissions().add(submission);

        session.persist(assignment);
        return submission;
    }
    return null;
}

From source file:org.springframework.orm.hibernate4.HibernateTemplate.java

License:Apache License

@Override
public void lock(final Object entity, final LockMode lockMode) throws DataAccessException {
    executeWithNativeSession(new HibernateCallback<Object>() {
        @Override/*from   w w w  . j a  v  a 2s.  co  m*/
        public Object doInHibernate(Session session) throws HibernateException {
            session.buildLockRequest(new LockOptions(lockMode)).lock(entity);
            return null;
        }
    });
}

From source file:org.springframework.orm.hibernate4.HibernateTemplate.java

License:Apache License

@Override
public void lock(final String entityName, final Object entity, final LockMode lockMode)
        throws DataAccessException {

    executeWithNativeSession(new HibernateCallback<Object>() {
        @Override// w w  w .  j a v a2  s .  c om
        public Object doInHibernate(Session session) throws HibernateException {
            session.buildLockRequest(new LockOptions(lockMode)).lock(entityName, entity);
            return null;
        }
    });
}

From source file:org.springframework.orm.hibernate4.HibernateTemplate.java

License:Apache License

@Override
public void update(final Object entity, final LockMode lockMode) throws DataAccessException {
    executeWithNativeSession(new HibernateCallback<Object>() {
        @Override/*  w ww. j ava2  s .  co  m*/
        public Object doInHibernate(Session session) throws HibernateException {
            checkWriteOperationAllowed(session);
            session.update(entity);
            if (lockMode != null) {
                session.buildLockRequest(new LockOptions(lockMode)).lock(entity);
            }
            return null;
        }
    });
}