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.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java

@Override
public int removeFinishedTasks(final int secondsAgo, final String namespace, final String clusterName,
        final String taskName) {
    beginTransaction();//from   w  w w  .  j av a2s . co m
    List<TaskEntity> finishedTasks;
    if (Strings.isNullOrEmpty(namespace)) {
        if (Strings.isNullOrEmpty(taskName)) {
            finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithState")
                    .setParameter("state", TaskState.DONE.intValue())
                    .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
        } else {
            finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateAndName")
                    .setParameter("state", TaskState.DONE.intValue()).setParameter("name", taskName)
                    .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
        }
    } else {
        if (Strings.isNullOrEmpty(clusterName)) {
            if (Strings.isNullOrEmpty(taskName)) {
                finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateFromNamespace")
                        .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace)
                        .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
            } else {
                finishedTasks = getEntityManager()
                        .createNamedQuery("task.peekTasksWithStateAndNameFromNamespace")
                        .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace)
                        .setParameter("name", taskName).setLockMode(LockModeType.PESSIMISTIC_WRITE)
                        .getResultList();
            }
        } else {
            if (Strings.isNullOrEmpty(taskName)) {
                finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateFromCluster")
                        .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace)
                        .setParameter("name", clusterName).setLockMode(LockModeType.PESSIMISTIC_WRITE)
                        .getResultList();
            } else {
                finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateAndNameFromCluster")
                        .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace)
                        .setParameter("name", taskName).setParameter("clusterName", clusterName)
                        .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
            }
        }
    }

    List<TaskEntity> removingTasks = finishedTasks.stream()
            .filter(t -> DateUtils.addSeconds(t.getCreatedAt(), secondsAgo).before(new Date()))
            .collect(Collectors.toList());
    removingTasks.stream().forEach(t -> getEntityManager().remove(t));
    getEntityManager().getTransaction().commit();
    return removingTasks.size();
}

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

public void update(Order order, Admin operator) {
    Assert.notNull(order);//ww  w .j a  v  a 2  s. c o  m

    Order pOrder = orderDao.find(order.getId());

    if (pOrder.getIsAllocatedStock()) {
        for (OrderItem orderItem : pOrder.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);
                }
            }
        }
        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);
                    productDao.flush();
                    staticService.build(product);
                }
            }
        }
    }

    orderDao.merge(order);

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

From source file:ext.msg.model.Message.java

public static boolean deleteMessageBySenderRevicer(Long senderId, Long consumeId, Collection<?> msgTypes) {
    List<Message> resultList = JPA.em().createQuery(
            "from Message m where m.senderOnly = :senderId and m.consumeOnly = :consumeId and m.msgType in (:msgTypes)",
            Message.class).setParameter("senderId", senderId.toString())
            .setParameter("consumeId", consumeId.toString()).setParameter("msgTypes", msgTypes)
            .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList();
    if (CollectionUtils.isEmpty(resultList)) {
        return false;
    }//from  ww  w. j a va  2s  . co m
    for (Message message : resultList)
        JPA.em().remove(message);
    return true;
}

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

@Override
public void deleteJob(int idJob) {
    jqmlogger.trace("Job status number " + idJob + " will be deleted");
    EntityManager em = null;/*from w  ww .jav  a 2  s. c  om*/

    try {
        em = getEm();

        // Two transactions against deadlock.
        JobInstance job = em.find(JobInstance.class, idJob);
        em.getTransaction().begin();
        em.refresh(job, LockModeType.PESSIMISTIC_WRITE);
        if (job.getState().equals(State.SUBMITTED)) {
            job.setState(State.CANCELLED);
        }
        em.getTransaction().commit();

        if (!job.getState().equals(State.CANCELLED)) {
            // Job is not in queue anymore - just return.
            return;
        }

        em.getTransaction().begin();
        em.createQuery("DELETE FROM Message WHERE ji = :i").setParameter("i", job.getId()).executeUpdate();
        em.createQuery("DELETE FROM RuntimeParameter WHERE ji = :i").setParameter("i", job.getId())
                .executeUpdate();
        em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate();
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException(
                "An attempt was made to delete a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("could not delete a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

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

public void complete(Order order, Admin operator) {
    Assert.notNull(order);//from w w w.j  a  v  a2  s .  co m

    Member member = order.getMember();
    memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);

    if (order.getShippingStatus() == ShippingStatus.partialShipment
            || order.getShippingStatus() == ShippingStatus.shipped) {
        member.setPoint(member.getPoint() + order.getPoint());
        for (Coupon coupon : order.getCoupons()) {
            couponCodeDao.build(coupon, member);
        }
    }

    if (order.getShippingStatus() == ShippingStatus.unshipped
            || order.getShippingStatus() == ShippingStatus.returned) {
        CouponCode couponCode = order.getCouponCode();
        if (couponCode != null) {
            couponCode.setIsUsed(false);
            couponCode.setUsedDate(null);
            couponCodeDao.merge(couponCode);

            order.setCouponCode(null);
            orderDao.merge(order);
        }
    }

    member.setAmount(member.getAmount().add(order.getAmountPaid()));
    if (!member.getMemberRank().getIsSpecial()) {
        MemberRank memberRank = memberRankDao.findByAmount(member.getAmount());
        if (memberRank != null && memberRank.getAmount().compareTo(member.getMemberRank().getAmount()) > 0) {
            member.setMemberRank(memberRank);
        }
    }
    memberDao.merge(member);

    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();
                    staticService.build(product);
                }
            }
        }
        order.setIsAllocatedStock(false);
    }

    for (OrderItem orderItem : order.getOrderItems()) {
        if (orderItem != null) {
            Product product = orderItem.getProduct();
            productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
            if (product != null) {
                Integer quantity = orderItem.getQuantity();
                Calendar nowCalendar = Calendar.getInstance();
                Calendar weekSalesCalendar = DateUtils.toCalendar(product.getWeekSalesDate());
                Calendar monthSalesCalendar = DateUtils.toCalendar(product.getMonthSalesDate());
                if (nowCalendar.get(Calendar.YEAR) != weekSalesCalendar.get(Calendar.YEAR) || nowCalendar
                        .get(Calendar.WEEK_OF_YEAR) > weekSalesCalendar.get(Calendar.WEEK_OF_YEAR)) {
                    product.setWeekSales((long) quantity);
                } else {
                    product.setWeekSales(product.getWeekSales() + quantity);
                }
                if (nowCalendar.get(Calendar.YEAR) != monthSalesCalendar.get(Calendar.YEAR)
                        || nowCalendar.get(Calendar.MONTH) > monthSalesCalendar.get(Calendar.MONTH)) {
                    product.setMonthSales((long) quantity);
                } else {
                    product.setMonthSales(product.getMonthSales() + quantity);
                }
                product.setSales(product.getSales() + quantity);
                product.setWeekSalesDate(new Date());
                product.setMonthSalesDate(new Date());
                productDao.merge(product);
                orderDao.flush();
                staticService.build(product);
            }
        }
    }

    order.setOrderStatus(OrderStatus.completed);
    order.setExpire(null);
    orderDao.merge(order);

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

From source file:com.tesora.dve.common.catalog.CatalogDAO.java

public <T> void refreshForLock(T o) {
    em.get().refresh(o, LockModeType.PESSIMISTIC_WRITE);
}

From source file:de.micromata.genome.jpa.Emgr.java

/**
 * Set the the query to use select for update.
 *
 * @param query the query//from  w w  w . j a v  a 2  s.co m
 * @param lockTimetimeInMs the lock timetime in ms
 */
@Override
public void setSelectForUpdate(Query query, int lockTimetimeInMs) {
    query.setHint(AvailableSettings.LOCK_TIMEOUT, lockTimetimeInMs);
    setQueryTimeout(query, lockTimetimeInMs);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
}

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

public void cancel(Order order, Admin operator) {
    Assert.notNull(order);//from www . ja  v a  2s  .  c  o  m

    CouponCode couponCode = order.getCouponCode();
    if (couponCode != null) {
        couponCode.setIsUsed(false);
        couponCode.setUsedDate(null);
        couponCodeDao.merge(couponCode);

        order.setCouponCode(null);
        orderDao.merge(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();
                    staticService.build(product);
                }
            }
        }
        order.setIsAllocatedStock(false);
    }

    order.setOrderStatus(OrderStatus.cancelled);
    order.setExpire(null);
    orderDao.merge(order);

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

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

public void payment(Order order, Payment payment, Admin operator) {
    Assert.notNull(order);// www  .j a v a  2s  .c  o m
    Assert.notNull(payment);

    orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

    payment.setOrder(order);
    paymentDao.merge(payment);
    if (payment.getMethod() == Payment.Method.deposit) {
        Member member = order.getMember();
        memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);
        member.setBalance(member.getBalance().subtract(payment.getAmount()));
        memberDao.merge(member);

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

    Setting setting = SettingUtils.get();
    if (!order.getIsAllocatedStock() && setting.getStockAllocationTime() == StockAllocationTime.payment) {
        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);
    }

    order.setAmountPaid(order.getAmountPaid().add(payment.getAmount()));
    order.setFee(payment.getFee());
    order.setExpire(null);
    if (order.getAmountPaid().compareTo(order.getAmount()) >= 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.paid);
    } else if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0) {
        order.setOrderStatus(OrderStatus.confirmed);
        order.setPaymentStatus(PaymentStatus.partialPayment);
    }
    orderDao.merge(order);

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

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

@Override
public void setJobQueue(int idJob, int idQueue) {
    EntityManager em = null;//from  w w w  .ja  v a  2s .  co  m
    JobInstance ji = null;
    Queue q = null;

    try {
        em = getEm();
        q = em.find(Queue.class, idQueue);
    } catch (NoResultException e) {
        closeQuietly(em);
        throw new JqmClientException("Queue does not exist");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Cannot retrieve queue", e);
    }

    try {
        em.getTransaction().begin();
        ji = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_WRITE);
        if (ji == null || !ji.getState().equals(State.SUBMITTED)) {
            throw new NoResultException();
        }
        ji.setQueue(q);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmClientException("Job instance does not exist or has already started");
    } catch (Exception e) {
        throw new JqmClientException("could not change the queue of a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}