Example usage for org.hibernate LockMode UPGRADE

List of usage examples for org.hibernate LockMode UPGRADE

Introduction

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

Prototype

LockMode UPGRADE

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

Click Source Link

Document

An upgrade lock.

Usage

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

protected void lockReadFolder(RepoFolder folder) {
    HibernateTemplate template = getHibernateTemplate();
    Session session = template.getSessionFactory().getCurrentSession();
    LockMode folderLockMode = session.getCurrentLockMode(folder);
    if (LockMode.READ.equals(folderLockMode)) {
        String currentURI = folder.getURI();

        //refresh and lock the parent
        template.refresh(folder, LockMode.UPGRADE);

        //check whether the parent URI has changed
        if (!currentURI.equals(folder.getURI())) {
            throw new JSException("jsexception.folder.moved", new Object[] { currentURI, folder.getURI() });
        }/*w  w  w. j a v  a 2 s  . c  om*/
    }
}

From source file:com.joe.utilities.core.configuration.admin.repository.ConfigurationRepositoryImpl.java

License:Open Source License

public IPropertyValue getSystemAssignedID(String key) {

    final List<String> interactionSysIds = new ArrayList<String>();
    interactionSysIds.add("SYSGENINTERACTIONID");
    interactionSysIds.add("SYSGENTOPICID");

    log.debug("ConfigurationRepositoryImpl.getSystemAssignedID() called");
    if (key == null) {
        return null;
    }/*  w  w w . j  a  v  a  2s.  c  o m*/

    // Create pessimistic lock to guard against multi-threaded access to the increment logic below

    PropertyValue property = null;
    ApplicationConfiguration appConfig = (ApplicationConfiguration) getHibernateTemplate()
            .get(ApplicationConfiguration.class, key, LockMode.UPGRADE);
    if (appConfig != null) {
        int updatedValue = Integer.parseInt(appConfig.getValue());
        appConfig.setValue(String.valueOf(++updatedValue));
        getHibernateTemplate().saveOrUpdate(appConfig);
        if (interactionSysIds.contains(key)) {
            property = new PropertyValue(key, appConfig.getValue());
        } else {
            property = new PropertyValue(key, "T" + appConfig.getValue());
        }
    }

    return property;

}

From source file:com.jvoid.persistence.hibernate.GenericHibernateDAO.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*  w  ww  .j  a  v  a2  s .  c om*/
public T findById(ID id, boolean lock) {
    T entity;
    try {
        if (lock) {
            entity = (T) getSession().get(getPersistentClass(), id, LockMode.UPGRADE);
        } else {
            entity = (T) getSession().get(getPersistentClass(), id);
        }
        return entity;
    } catch (Exception e) {
        // e.printStackTrace();
        getTransaction().rollback();
        return null;
    }
}

From source file:com.npower.dm.hibernate.management.ProvisionJobManagementBeanImpl.java

License:Open Source License

public void update(ProvisionJob job) throws DMException {
    try {// w  ww .  jav  a 2  s .  c om
        Session session = this.getHibernateSession();
        job.setLastUpdatedTime(new Date());
        session.saveOrUpdate(job);
        session.flush();
        session.refresh(job, LockMode.UPGRADE);
        //session.refresh(job, LockMode.UPGRADE);

        // Update all of status related with the job.
        String newState = job.getState();
        this.updateJobState(job.getID(), newState);
    } catch (HibernateException e) {
        throw new DMException(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 . ja  v  a 2s  . com
    sessionFactory.getCurrentSession().getTransaction().commit();
    sessionFactory.getCurrentSession().close();
    sessionFactory.close();
    return true;
}

From source file:com.redhat.rhn.common.hibernate.HibernateFactory.java

License:Open Source License

/**
 * Return a locked persistent instance of the given entity class with
 * the given identifier, or null if there is no such persistent instance.
 * (If the instance, or a proxy for the instance, is already associated
 * with the session, return that instance or proxy.)
 * @param clazz a persistent class// w  w  w  .j  a va 2s  .c  o m
 * @param id an identifier
 * @return Object persistent instance or null
 */
protected Object lockObject(Class clazz, Serializable id) {
    Object retval = null;
    Session session = null;

    try {
        session = HibernateFactory.getSession();

        retval = session.get(clazz, id, LockMode.UPGRADE);
    } catch (MappingException me) {
        getLogger().error("Mapping not found for " + clazz.getName(), me);

    } catch (HibernateException he) {
        getLogger().error("Hibernate exception: " + he.toString());
    }

    return retval;
}

From source file:com.salesmanager.core.service.system.impl.dao.SystemDao.java

License:Open Source License

public long incrementOrderIdCounter() throws RuntimeException {

    try {//  w ww .j  av a2  s.  c  o m

        // Query q =
        // super.getSession().createQuery("from CentralSequencer c where c.centralSequencerId=:p").setMaxResults(1);
        // q.setParameter("p", 1);
        // q.setLockMode("c", LockMode.UPGRADE);

        CentralSequencer sequence = (CentralSequencer) super.getHibernateTemplate().get(CentralSequencer.class,
                new Integer(1), LockMode.UPGRADE);

        // CentralSequencer sequence =
        // (CentralSequencer)session.get(CentralSequencer.class, new
        // Integer(1), LockMode.UPGRADE);

        // CentralSequencer sequence = (CentralSequencer)q.uniqueResult();
        long currentCount = sequence.getOrderIdNextValue();
        long newCount = currentCount + 1;
        sequence.setOrderIdNextValue(newCount);
        // super.getHibernateTemplate().update(sequence);
        return newCount;

    } catch (RuntimeException e) {
        log.error(e);
        throw e;
    }

}

From source file:com.sapienter.jbilling.server.util.db.AbstractDAS.java

License:Open Source License

/**
 * This will lock the row for the duration of this transaction. Or wait until the row is
 * unlocked if it is already locked. It genererates a select ... for update
 * @param id//from  w w  w. j a  v  a  2  s. c o m
 * @return
 */
@SuppressWarnings("unchecked")
public T findForUpdate(Serializable id) {
    if (id == null) {
        return null;
    }
    return getHibernateTemplate().get(getPersistentClass(), id, LockMode.UPGRADE);
}

From source file:com.test.HibernateDerbyLockingTest.java

License:Apache License

public void runTest(final SessionFactory sessionFactory) throws Exception {
    Person person = new Person();

    Session session = sessionFactory.openSession();
    session.save(person);//w  w w.ja  v  a  2s .co  m
    session.flush();
    session.close();

    final String id = person.getId();
    final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

    ExecutorService executorService = Executors.newCachedThreadPool();
    Future<?> submit = executorService.submit(new Runnable() {
        public void run() {
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            session.load(Person.class, id, LockMode.UPGRADE);
            try {
                Thread.sleep(2000);
            } catch (Throwable t) {
            }
            System.out.println("one");
            queue.add("one");
            try {
                Thread.sleep(500);
            } catch (Throwable t) {
            }
            transaction.commit();
            session.flush();
            session.close();
        }
    });
    Thread.sleep(500);
    Future<?> submit2 = executorService.submit(new Runnable() {
        public void run() {
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            session.load(Person.class, id, LockMode.UPGRADE);
            queue.add("two");
            System.out.println("two");
            transaction.commit();
            session.flush();
            session.close();
        }
    });
    submit.get();
    submit2.get();
    assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
    assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
}

From source file:com.viettel.model.GenericHibernateDAO.java

License:Open Source License

/**
 * Return the persistent instance of the given entity class with the given
 * identifier, assuming that the instance exists.
 *
 * @param sessionName Name of hibernate session
 * @param id A valid identifier of an existing persistent instance of the
 * class//from w  w  w .j  a  va 2  s .co  m
 * @param lock Lock the entity?
 * @return An entity
 */
@SuppressWarnings("unchecked")
public T findById(String sessionName, ID id, boolean lock) {
    try {
        T entity;
        if (lock) {
            entity = (T) getSession(sessionName).get(getPersistentClass(), id, LockMode.UPGRADE);
        } else {
            entity = (T) getSession(sessionName).get(getPersistentClass(), id);
        }
        return entity;
    } catch (RuntimeException e) {
        throw e;
    } finally {
        this.releaseResource();
    }
}