Example usage for org.hibernate LockMode PESSIMISTIC_WRITE

List of usage examples for org.hibernate LockMode PESSIMISTIC_WRITE

Introduction

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

Prototype

LockMode PESSIMISTIC_WRITE

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

Click Source Link

Document

Transaction will obtain a database lock immediately.

Usage

From source file:org.grails.orm.hibernate.query.AbstractHibernateQuery.java

License:Apache License

@Override
public Query lock(boolean lock) {
    criteria.setCacheable(false);//from  w ww .j a va2s  .  co m
    criteria.setLockMode(LockMode.PESSIMISTIC_WRITE);
    return super.lock(lock);
}

From source file:org.infinispan.test.hibernate.cache.commons.functional.ConcurrentWriteTest.java

License:LGPL

/**
 * remove existing 'contact' from customer's list of contacts
 *
 * @param customerId/*from  w  ww .j  a v a 2 s  . co  m*/
 * @throws IllegalStateException
 *            if customer does not own a contact
 */
private void removeContact(Integer customerId) throws Exception {
    assert customerId != null;

    withTxSession(s -> {
        Customer customer = s.load(Customer.class, customerId);
        Set<Contact> contacts = customer.getContacts();
        if (contacts.size() != 1) {
            throw new IllegalStateException("can't remove contact: customer id=" + customerId
                    + " expected exactly 1 contact, " + "actual count=" + contacts.size());
        }

        Contact contact = contacts.iterator().next();
        // H2 version 1.3 (without MVCC fails with deadlock on Contacts/Customers modification, therefore,
        // we have to enforce locking Contacts first
        s.lock(contact, LockMode.PESSIMISTIC_WRITE);
        contacts.remove(contact);
        contact.setCustomer(null);

        // explicitly delete Contact because hbm has no 'DELETE_ORPHAN' cascade?
        // getEnvironment().getSessionFactory().getCurrentSession().delete(contact); //appears to
        // not be needed

        // assuming contact is persisted via cascade from customer

        if (TERMINATE_ALL_USERS) {
            markRollbackOnly(s);
        }
    });
}

From source file:org.intelligentsia.utility.generator.TableGenerator.java

License:Apache License

public void configure(final DataSource dataSource, final Dialect dialect, final String tableName,
        final String keyValue, final long initialValue) {
    this.tableName = tableName;
    this.dataSource = dataSource;
    insert = new StringBuilder("INSERT into ").append(tableName).append(" values ('").append(keyValue)
            .append("', ").append(initialValue).append(")").toString();
    query = new StringBuilder("select NEXT_VAL from ")
            .append(dialect.appendLockHint(new LockOptions(LockMode.PESSIMISTIC_WRITE), tableName))
            .append(" where VAL_ID='").append(keyValue).append("' ").append(dialect.getForUpdateString())
            .toString();//from w w  w . ja v  a 2 s .c  o  m
    update = new StringBuilder("update ").append(tableName).append(" set NEXT_VAL=? WHERE VAL_ID='")
            .append(keyValue).append("' AND NEXT_VAL=?").toString();
}

From source file:org.jboss.processFlow.knowledgeService.JpaKnowledgeSessionPool.java

License:Open Source License

public Integer getSessionId(Long pInstanceId) {
    EntityManager em = emf.createEntityManager();
    try {//from  www  .ja va  2s .c o m
        Session session = (Session) em.getDelegate();
        SessionProcessXref xref = (SessionProcessXref) session
                .createQuery(
                        "SELECT xref FROM SessionProcessXref xref where xref.processInstanceId=:pInstanceId")
                .setLockMode("xref", LockMode.PESSIMISTIC_WRITE).setParameter("pInstanceId", pInstanceId)
                .uniqueResult();
        if (xref == null)
            throw new RuntimeException(
                    "getSessionId() unable to find SessionProcessXref in db for pInstanceId = " + pInstanceId);
        return xref.getSessionId();
    } finally {
        em.close();
    }
}

From source file:org.jpos.ee.SeqNoManager.java

License:Open Source License

private SeqNo getOrCreate(String id) {
    SeqNo seq = db.session().get(SeqNo.class, id, LockMode.PESSIMISTIC_WRITE);
    if (seq == null) {
        create(id);/* w w w.jav  a  2s  .  co m*/
        seq = db.session().get(SeqNo.class, id, LockMode.PESSIMISTIC_WRITE);
    }
    return seq;
}

From source file:org.mzd.shap.spring.orm.BaseDaoSpringHibernate.java

License:Open Source License

public void refreshToWrite(ENTITY entity) {
    getHibernateTemplate().refresh(entity, LockMode.PESSIMISTIC_WRITE);
}

From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java

License:Open Source License

/**
 * Returns the next sequence number of the Document Type defined for the Organization and document
 * category./*from w  w  w.ja  v  a  2  s .c  o  m*/
 * 
 * @param docType
 *          Document type of the document
 * @param tableName
 *          the name of the table from which the sequence will be taken if the Document Type does
 *          not have any sequence associated.
 * @param updateNext
 *          Flag to update the current number of the sequence
 * @return the next sequence number of the Document Type defined for the Organization and document
 *         category. Null if no sequence is found.
 */
public static String getDocumentNo(DocumentType docType, String tableName, boolean updateNext) {
    String nextDocNumber = "";
    if (docType != null) {
        Sequence seq = docType.getDocumentSequence();
        if (seq == null && tableName != null) {
            OBCriteria<Sequence> obcSeq = OBDal.getInstance().createCriteria(Sequence.class);
            obcSeq.add(Restrictions.eq(Sequence.PROPERTY_NAME, tableName));
            obcSeq.setLockMode(LockMode.PESSIMISTIC_WRITE);
            if (obcSeq != null && obcSeq.list().size() > 0) {
                seq = obcSeq.list().get(0);
            }
        }
        if (seq != null) {
            if (seq.getPrefix() != null)
                nextDocNumber = seq.getPrefix();
            nextDocNumber += seq.getNextAssignedNumber().toString();
            if (seq.getSuffix() != null)
                nextDocNumber += seq.getSuffix();
            if (updateNext) {
                seq.setNextAssignedNumber(seq.getNextAssignedNumber() + seq.getIncrementBy());
                OBDal.getInstance().save(seq);
                // OBDal.getInstance().flush();
            }
        }
    }

    return nextDocNumber;
}

From source file:org.opennms.netmgt.dao.hibernate.AbstractDaoHibernate.java

License:Open Source License

/** {@inheritDoc} */
@Override
public void lock() {
    getHibernateTemplate().get(AccessLock.class, m_lockName, LockMode.PESSIMISTIC_WRITE);
}

From source file:org.projectforge.address.PersonalAddressDao.java

License:Open Source License

/**
 * @param obj//from w  w w  .  j  a  v  a 2 s.  co m
 * @return true, if already existing entry was updated, otherwise false (e. g. if no entry exists for update).
 */
private boolean internalUpdate(final PersonalAddressDO obj) {
    PersonalAddressDO dbObj = null;
    if (obj.getId() != null) {
        dbObj = getHibernateTemplate().load(PersonalAddressDO.class, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    }
    if (dbObj == null) {
        dbObj = getByAddressId(obj.getAddressId());
    }
    if (dbObj == null) {
        return false;
    }
    checkAccess(dbObj);
    Validate.isTrue(ObjectUtils.equals(dbObj.getAddressId(), obj.getAddressId()));
    obj.setId(dbObj.getId());
    if (isEmpty(obj) == true) {
        // Is empty, so delete this entry:
        getHibernateTemplate().delete(dbObj);
        log.info("Empty object deleted: " + obj.toString());
        return true;
    }
    // Copy all values of modified user to database object.
    final ModificationStatus modified = dbObj.copyValuesFrom(obj, "owner", "address", "id");
    if (modified == ModificationStatus.MAJOR) {
        dbObj.setLastUpdate();
        log.info("Object updated: " + dbObj.toString());
    }
    return true;
}

From source file:org.projectforge.business.address.PersonalAddressDao.java

License:Open Source License

/**
 * @param obj/*ww w  .j a  va2 s. c  o  m*/
 * @return true, if already existing entry was updated, otherwise false (e. g. if no entry exists for update).
 */
private boolean internalUpdate(final PersonalAddressDO obj) {
    PersonalAddressDO dbObj = null;
    if (obj.getId() != null) {
        dbObj = hibernateTemplate.load(PersonalAddressDO.class, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    }
    if (dbObj == null) {
        dbObj = getByAddressId(obj.getAddressId());
    }
    if (dbObj == null) {
        return false;
    }
    checkAccess(dbObj);
    Validate.isTrue(ObjectUtils.equals(dbObj.getAddressId(), obj.getAddressId()));
    obj.setId(dbObj.getId());
    // Copy all values of modified user to database object.
    final ModificationStatus modified = dbObj.copyValuesFrom(obj, "owner", "address", "id");
    if (modified == ModificationStatus.MAJOR) {
        dbObj.setLastUpdate();
        log.info("Object updated: " + dbObj.toString());
    }
    return true;
}