Example usage for javax.persistence LockModeType OPTIMISTIC

List of usage examples for javax.persistence LockModeType OPTIMISTIC

Introduction

In this page you can find the example usage for javax.persistence LockModeType OPTIMISTIC.

Prototype

LockModeType OPTIMISTIC

To view the source code for javax.persistence LockModeType OPTIMISTIC.

Click Source Link

Document

Optimistic lock.

Usage

From source file:com.czecht.architecture.ddd.annotations.support.infrastructure.repository.jpa.GenericJpaRepository.java

@Transactional(propagation = Propagation.SUPPORTS)
public A load(AggregateId id) {
    //lock to be sure when creating other objects based on values of this aggregate
    A aggregate = entityManager.find(clazz, id, LockModeType.OPTIMISTIC);

    if (aggregate == null)
        throw new RuntimeException("Aggregate " + clazz.getCanonicalName() + " id = " + id + " does not exist");

    if (aggregate.isRemoved())
        throw new RuntimeException("Aggragate + " + id + " is removed.");

    spring.autowireBean(aggregate);/* w  w w.ja v  a 2s .c o  m*/

    return aggregate;
}

From source file:net.kamhon.ieagle.dao.Jpa2Dao.java

@SuppressWarnings("unchecked")
public T getReadonly(final PK serializablekey) {
    return em.find((Class<T>) t.getClass(), serializablekey, LockModeType.OPTIMISTIC);
}

From source file:net.kamhon.ieagle.dao.JpaDao.java

@Override
public T getReadonly(final Class<T> clazz, final Serializable serializablekey) {
    return getJpaTemplate().execute(new JpaCallback<T>() {
        @Override//  www. j  a  v a 2 s .  c  o m
        public T doInJpa(EntityManager em) throws PersistenceException {
            return em.find(clazz, serializablekey, LockModeType.OPTIMISTIC);
        }
    });
}

From source file:org.cleverbus.core.common.dao.ExternalCallDaoJpaImpl.java

@Override
@Transactional(propagation = Propagation.MANDATORY)
public void lockExternalCall(ExternalCall extCall) throws PersistenceException {
    Assert.notNull(extCall, "the extCall must not be null");
    Assert.isTrue(extCall.getState() != ExternalCallStateEnum.PROCESSING,
            "the extCall must not be locked in a processing state");

    Assert.isTrue(em.contains(extCall), "the extCall must be attached");
    // note: https://blogs.oracle.com/carolmcdonald/entry/jpa_2_0_concurrency_and
    em.lock(extCall, LockModeType.OPTIMISTIC);
    extCall.setState(ExternalCallStateEnum.PROCESSING);
}

From source file:se.nrm.dina.data.jpa.impl.DinaDaoImpl.java

@Override
public T findById(int id, Class<T> clazz, boolean isVersioned) {
    logger.info("findById - class : {} - id : {}", clazz, id);

    T tmp = null;/*www .jav a 2 s.  c om*/
    try {
        if (isVersioned) {
            tmp = entityManager.find(clazz, id, LockModeType.OPTIMISTIC);
        } else {
            tmp = entityManager.find(clazz, id, LockModeType.PESSIMISTIC_READ);
        }
        entityManager.flush();
        return tmp;
    } catch (OptimisticLockException ex) {
        entityManager.refresh(tmp);
        throw new DinaDatabaseException(new ErrorBean(clazz.getSimpleName(), ex.getMessage()), 400);
    } catch (Exception ex) {
        throw new DinaDatabaseException(new ErrorBean(clazz.getSimpleName(), ex.getMessage()), 400);
    }
}

From source file:org.key2gym.business.services.CashServiceBean.java

@Override
public void recordCashAdjustment(CashAdjustmentDTO cashAdjustment)
        throws ValidationException, SecurityViolationException {

    if (!callerHasRole(SecurityRoles.MANAGER)) {
        throw new SecurityViolationException(getString("Security.Operation.Denied"));
    }/*from w  w  w  .  j ava 2s .  c om*/

    if (cashAdjustment == null) {
        throw new NullPointerException("The cashAdjustment is null."); //NOI18N
    }

    if (cashAdjustment.getDate() == null) {
        throw new NullPointerException("The cashAdjustment.getDate() is null."); //NOI18N
    }

    if (cashAdjustment.getAmount() == null) {
        throw new NullPointerException("The cashAdjustment.getAmount() is null."); //NOI18N
    }

    validateAmount(cashAdjustment.getAmount());

    if (cashAdjustment.getNote() == null) {
        throw new NullPointerException("The cashAdjustment.getNote() is null."); //NOI18N
    }

    CashAdjustment entityCashAdjustment = em.find(CashAdjustment.class, cashAdjustment.getDate().toDate(),
            LockModeType.OPTIMISTIC);

    if (entityCashAdjustment == null) {
        entityCashAdjustment = new CashAdjustment();
        entityCashAdjustment.setDateRecorded(cashAdjustment.getDate().toDate());
        entityCashAdjustment.setAmount(cashAdjustment.getAmount());
        entityCashAdjustment.setNote(cashAdjustment.getNote());

        em.persist(entityCashAdjustment);
    } else {
        entityCashAdjustment.setDateRecorded(cashAdjustment.getDate().toDate());
        entityCashAdjustment.setAmount(cashAdjustment.getAmount());
        entityCashAdjustment.setNote(cashAdjustment.getNote());
    }

    em.flush();
}

From source file:se.nrm.dina.data.jpa.DinaDaoImpl.java

@Override
public T findById(int id, Class<T> clazz) {
    logger.info("findById - class : {} - id : {}", clazz, id);

    // Entity has no version can not have Optimistic lock
    if (clazz.getSimpleName().equals(Recordsetitem.class.getSimpleName())
            || clazz.getSimpleName().equals(Sppermission.class.getSimpleName())
            || clazz.getSimpleName().equals(Workbenchrow.class.getSimpleName())
            || clazz.getSimpleName().equals(Workbenchdataitem.class.getSimpleName())
            || clazz.getSimpleName().equals(Workbenchrowimage.class.getSimpleName())
            || clazz.getSimpleName().equals(Geoname.class.getSimpleName())) {

        return entityManager.find(clazz, id, LockModeType.PESSIMISTIC_WRITE);
    }//from  www  .  jav a  2s  .  c  o m

    T tmp = null;
    try {
        tmp = entityManager.find(clazz, id, LockModeType.OPTIMISTIC);
        entityManager.flush();
    } catch (OptimisticLockException ex) {
        entityManager.refresh(tmp);
        logger.warn(ex.getMessage());
    } catch (Exception ex) {
        logger.warn(ex.getMessage());
    }
    return tmp;
}

From source file:bq.jpa.demo.lock.service.LockService.java

/**
 * Statistic//  w  w  w.j  av  a  2 s  .  c o m
 */
@Transactional
public void doStatisticSalary() {
    try {
        lock.lock();

        TypedQuery<Employee> query = em.createQuery("SELECT e FROM jpa_lock_employee e", Employee.class);
        List<Employee> results = query.getResultList();
        System.out.println("[thread-reading] query employees");

        for (Employee employee : results) {
            em.lock(employee, LockModeType.OPTIMISTIC);
            em.flush();
        }
        System.out.println("[thread-reading] lock employees");
        writeCondition.signal();
        readCondition.await();
        Thread.sleep(1000);

        float totalSalary = 0f;
        for (Employee employee : results) {
            totalSalary += employee.getSalary();
        }

        System.out.println("[thread-reading] total salary is :" + totalSalary);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

From source file:op.care.med.inventory.DlgOpenStock.java

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
    if (cmbBestID.getSelectedIndex() > 0) {
        EntityManager em = OPDE.createEM();
        try {/*ww w. ja  v a 2  s. co m*/
            em.getTransaction().begin();
            medStock = em.merge((MedStock) cmbBestID.getSelectedItem());
            em.lock(medStock, LockModeType.OPTIMISTIC);
            em.lock(em.merge(medStock.getInventory().getResident()), LockModeType.OPTIMISTIC);

            medStock.setOpened(new Date());

            em.getTransaction().commit();
        } catch (javax.persistence.OptimisticLockException ole) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                OPDE.getMainframe().emptyFrame();
                OPDE.getMainframe().afterLogin();
            }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception e) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            OPDE.fatal(e);
        } finally {
            em.close();
        }
        dispose();
    }
}

From source file:op.care.values.PnlValues.java

private java.util.List<Component> addCommands() {
    java.util.List<Component> list = new ArrayList<Component>();

    JideButton controlButton = GUITools.createHyperlinkButton(
            SYSTools.xx("nursingrecords.vitalparameters.btnControlling.tooltip"), SYSConst.icon22magnify1,
            new ActionListener() {
                @Override//  w w  w .j a  va2  s.  co  m
                public void actionPerformed(ActionEvent actionEvent) {
                    if (!resident.isActive()) {
                        OPDE.getDisplayManager()
                                .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                        return;
                    }
                    new DlgValueControl(resident, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    Resident myResident = em.merge(resident);
                                    em.lock(myResident, LockModeType.OPTIMISTIC);
                                    myResident.setControlling((Properties) o);
                                    em.getTransaction().commit();

                                    resident = myResident;
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }

                            }
                        }
                    });
                }
            });
    list.add(controlButton);

    return list;
}