Example usage for javax.persistence LockModeType PESSIMISTIC_WRITE

List of usage examples for javax.persistence LockModeType PESSIMISTIC_WRITE

Introduction

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

Prototype

LockModeType PESSIMISTIC_WRITE

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

Click Source Link

Document

Pessimistic write lock.

Usage

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void setJobQueuePosition(int idJob, int position) {
    EntityManager em = null;/*w w w .j a  v a 2 s  . c  o m*/
    JobInstance ji = null;
    try {
        em = getEm();
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException(
                "Could not lock a job by the given ID. It may already have been executed or a timeout may have occurred.",
                e);
    }

    if (!ji.getState().equals(State.SUBMITTED)) {
        closeQuietly(em);
        throw new JqmInvalidRequestException(
                "Job is already set for execution. Too late to change its position in the queue");
    }

    try {
        int current = ji.getCurrentPosition(em);
        int betweenUp = 0;
        int betweenDown = 0;

        if (current == position) {
            // Nothing to do
            em.getTransaction().rollback();
            return;
        } else if (current < position) {
            betweenDown = position;
            betweenUp = position + 1;
        } else {
            betweenDown = position - 1;
            betweenUp = position;
        }

        // No locking - we'll deal with exceptions
        List<JobInstance> currentJobs = em
                .createQuery("SELECT ji from JobInstance ji ORDER BY ji.internalPosition", JobInstance.class)
                .setMaxResults(betweenUp).getResultList();

        if (currentJobs.isEmpty()) {
            ji.setInternalPosition(0);
        } else if (currentJobs.size() < betweenUp) {
            ji.setInternalPosition(currentJobs.get(currentJobs.size() - 1).getInternalPosition() + 0.00001);
        } else {
            // Normal case: put the JI between the two others.
            ji.setInternalPosition((currentJobs.get(betweenUp - 1).getInternalPosition()
                    + currentJobs.get(betweenDown - 1).getInternalPosition()) / 2);
        }
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new JqmClientException("could not change the queue position of a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:net.groupbuy.service.impl.OrderServiceImpl.java

public void refunds(Order order, Refunds refunds, Admin operator) {
    Assert.notNull(order);// ww  w .j  a  va  2  s.co  m
    Assert.notNull(refunds);

    orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

    refunds.setOrder(order);
    refundsDao.persist(refunds);
    if (refunds.getMethod() == Refunds.Method.deposit) {
        Member member = order.getMember();
        memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);
        member.setBalance(member.getBalance().add(refunds.getAmount()));
        memberDao.merge(member);

        Deposit deposit = new Deposit();
        deposit.setType(Deposit.Type.adminRefunds);
        deposit.setCredit(refunds.getAmount());
        deposit.setDebit(new BigDecimal(0));
        deposit.setBalance(member.getBalance());
        deposit.setOperator(operator != null ? operator.getUsername() : null);
        deposit.setMember(member);
        deposit.setOrder(order);
        depositDao.persist(deposit);
    }

    order.setAmountPaid(order.getAmountPaid().subtract(refunds.getAmount()));
    order.setExpire(null);
    if (order.getAmountPaid().compareTo(new BigDecimal(0)) == 0) {
        order.setPaymentStatus(PaymentStatus.refunded);
    } else if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) {
        order.setPaymentStatus(PaymentStatus.partialRefunds);
    }
    orderDao.merge(order);

    OrderLog orderLog = new OrderLog();
    orderLog.setType(Type.refunds);
    orderLog.setOperator(operator != null ? operator.getUsername() : null);
    orderLog.setOrder(order);
    orderLogDao.persist(orderLog);
}

From source file:net.groupbuy.service.impl.OrderServiceImpl.java

public void shipping(Order order, Shipping shipping, Admin operator) {
    Assert.notNull(order);//from  ww  w  . j  a va  2s  .  c  o  m
    Assert.notNull(shipping);
    Assert.notEmpty(shipping.getShippingItems());

    orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

    Setting setting = SettingUtils.get();
    if (!order.getIsAllocatedStock() && setting.getStockAllocationTime() == StockAllocationTime.ship) {
        for (OrderItem orderItem : order.getOrderItems()) {
            if (orderItem != null) {
                Product product = orderItem.getProduct();
                productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                if (product != null && product.getStock() != null) {
                    product.setAllocatedStock(product.getAllocatedStock()
                            + (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                    productDao.merge(product);
                    orderDao.flush();
                    staticService.build(product);
                }
            }
        }
        order.setIsAllocatedStock(true);
    }

    shipping.setOrder(order);
    shippingDao.persist(shipping);
    for (ShippingItem shippingItem : shipping.getShippingItems()) {
        OrderItem orderItem = order.getOrderItem(shippingItem.getSn());
        if (orderItem != null) {
            Product product = orderItem.getProduct();
            productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
            if (product != null) {
                if (product.getStock() != null) {
                    product.setStock(product.getStock() - shippingItem.getQuantity());
                    if (order.getIsAllocatedStock()) {
                        product.setAllocatedStock(product.getAllocatedStock() - shippingItem.getQuantity());
                    }
                }
                productDao.merge(product);
                orderDao.flush();
                staticService.build(product);
            }
            orderItemDao.lock(orderItem, LockModeType.PESSIMISTIC_WRITE);
            orderItem.setShippedQuantity(orderItem.getShippedQuantity() + shippingItem.getQuantity());
        }
    }
    if (order.getShippedQuantity() >= order.getQuantity()) {
        order.setShippingStatus(ShippingStatus.shipped);
        order.setIsAllocatedStock(false);
    } else if (order.getShippedQuantity() > 0) {
        order.setShippingStatus(ShippingStatus.partialShipment);
    }
    order.setExpire(null);
    orderDao.merge(order);

    OrderLog orderLog = new OrderLog();
    orderLog.setType(Type.shipping);
    orderLog.setOperator(operator != null ? operator.getUsername() : null);
    orderLog.setOrder(order);
    orderLogDao.persist(orderLog);
}

From source file:net.groupbuy.service.impl.OrderServiceImpl.java

public void returns(Order order, Returns returns, Admin operator) {
    Assert.notNull(order);/* ww  w.j  a v  a2 s .  c  om*/
    Assert.notNull(returns);
    Assert.notEmpty(returns.getReturnsItems());

    orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

    returns.setOrder(order);
    returnsDao.persist(returns);
    for (ReturnsItem returnsItem : returns.getReturnsItems()) {
        OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
        if (orderItem != null) {
            orderItemDao.lock(orderItem, LockModeType.PESSIMISTIC_WRITE);
            orderItem.setReturnQuantity(orderItem.getReturnQuantity() + returnsItem.getQuantity());
        }
    }
    if (order.getReturnQuantity() >= order.getShippedQuantity()) {
        order.setShippingStatus(ShippingStatus.returned);
    } else if (order.getReturnQuantity() > 0) {
        order.setShippingStatus(ShippingStatus.partialReturns);
    }
    order.setExpire(null);
    orderDao.merge(order);

    OrderLog orderLog = new OrderLog();
    orderLog.setType(Type.returns);
    orderLog.setOperator(operator != null ? operator.getUsername() : null);
    orderLog.setOrder(order);
    orderLogDao.persist(orderLog);
}

From source file:net.groupbuy.service.impl.OrderServiceImpl.java

@Override
public void delete(Order order) {
    if (order.getIsAllocatedStock()) {
        for (OrderItem orderItem : order.getOrderItems()) {
            if (orderItem != null) {
                Product product = orderItem.getProduct();
                productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                if (product != null && product.getStock() != null) {
                    product.setAllocatedStock(product.getAllocatedStock()
                            - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                    productDao.merge(product);
                    orderDao.flush();/* www.ja va 2  s  .c  o m*/
                    staticService.build(product);
                }
            }
        }
    }
    super.delete(order);
}

From source file:org.batoo.jpa.core.impl.criteria.QueryImpl.java

private List<X> getResultListImpl() {
    this.em.getSession().setLoadTracker();

    final Connection connection = this.em.getConnection();
    try {//from  w w  w  . j  a v a2 s .c o m
        final LockModeType lockMode = this.getLockMode();
        final boolean hasLock = (lockMode == LockModeType.PESSIMISTIC_READ)
                || (lockMode == LockModeType.PESSIMISTIC_WRITE)
                || (lockMode == LockModeType.PESSIMISTIC_FORCE_INCREMENT);
        if (hasLock) {
            this.sql = this.em.getJdbcAdaptor().applyLock(this.sql, lockMode);
        }

        final Object[] parameters = this.applyParameters(connection);

        return this.buildResultSet(connection, parameters);
    } finally {
        this.em.getSession().releaseLoadTracker();

        this.em.closeConnectionIfNecessary();
    }
}

From source file:org.candlepin.model.AbstractHibernateCurator.java

public List<E> lockAndLoadBatch(Iterable<String> ids, String entityName, String keyName) {
    List<E> result = new LinkedList<E>();

    if (ids != null && ids.iterator().hasNext()) {
        StringBuilder hql = new StringBuilder("SELECT obj FROM ").append(entityName).append(" obj WHERE ")
                .append(keyName).append(" IN (:ids)");

        Query query = this.getEntityManager().createQuery(hql.toString())
                .setLockMode(LockModeType.PESSIMISTIC_WRITE);

        for (List<String> block : Iterables.partition(ids, IN_OPERATOR_BLOCK_SIZE)) {
            query.setParameter("ids", block);
            result.addAll((List<E>) query.getResultList());
        }//from w  w w  .j  a  v  a2  s.co  m
        //In some situations, even after locking the entity we
        //got stale in the entity e.g. Pool.consumed
        //This refresh reloads the entity after the lock has
        //been issued.
        for (E e : result) {
            getEntityManager().refresh(e);
        }
    }

    return result;
}

From source file:org.candlepin.model.ConsumerCurator.java

/**
 * Apply a SELECT FOR UPDATE on a consumer.
 *
 * Note this method is not transactional.  It is meant to be used within
 * a larger transaction.  Starting a transaction, running a select for update,
 * and then ending the transaction is pointless.
 *
 * @return A consumer locked in the database
 *///from www  .j  av a2s.  c om
public Consumer lockAndLoad(Consumer c) {
    getEntityManager().lock(c, LockModeType.PESSIMISTIC_WRITE);
    return c;
}

From source file:org.exoplatform.social.addons.storage.RDBMSActivityStorageImpl.java

@Override
@ExoTransactional/*ww  w .j av  a 2 s.  c  o m*/
public void saveComment(ExoSocialActivity activity, ExoSocialActivity eXoComment)
        throws ActivityStorageException {
    ActivityEntity activityEntity = activityDAO.find(Long.valueOf(activity.getId()));
    try {
        EntityManagerHolder.get().lock(activityEntity, LockModeType.PESSIMISTIC_WRITE);

        CommentEntity commentEntity = convertCommentToCommentEntity(eXoComment);
        commentEntity.setActivity(activityEntity);
        //
        Identity commenter = identityStorage.findIdentityById(commentEntity.getPosterId());
        saveStreamItemForCommenter(commenter, activityEntity);
        mention(commenter, activityEntity, processMentions(eXoComment.getTitle()));
        //
        activityEntity.addComment(commentEntity);
        commentEntity = commentDAO.create(commentEntity);
        eXoComment.setId(getExoCommentID(commentEntity.getId()));
        //
        activityEntity.setMentionerIds(processMentionOfComment(activityEntity, commentEntity,
                activity.getMentionedIds(), processMentions(eXoComment.getTitle()), true));
        activityEntity.setUpdatedDate(new Date(System.currentTimeMillis()));
        activityDAO.update(activityEntity);
        //
        updateLastUpdatedForStreamItem(activityEntity);
        //
        activity = convertActivityEntityToActivity(activityEntity);
    } finally {
        EntityManagerHolder.get().lock(activityEntity, LockModeType.NONE);
    }

}