Example usage for javax.persistence EntityManager joinTransaction

List of usage examples for javax.persistence EntityManager joinTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager joinTransaction.

Prototype

public void joinTransaction();

Source Link

Document

Indicate to the entity manager that a JTA transaction is active and join the persistence context to it.

Usage

From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java

private <T> T createEntityManagerProxy(Class<T> interfaceClass, Object emProxy) {
    InvocationHandler handler = (proxy, method, args) -> {

        EntityManager em = entityManagerLocal.get() != null ? entityManagerLocal.get()
                : (EntityManager) emProxy;
        switch (method.getName()) {
        case "hashCode":
            return hashCode();
        case "equals":
            return (em == args[0]);
        case "toString":
            return "Camel EntityManager proxy [" + em.toString() + "]";
        }/*from ww w . j  a  v a  2s.c o m*/

        if (!em.isJoinedToTransaction()) {
            em.joinTransaction();
        }
        return method.invoke(em, args);
    };
    return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler);
}

From source file:org.fornax.cartridges.sculptor.framework.web.jpa.JpaFlowExecutionListener.java

public void sessionEnded(RequestContext context, FlowSession session, String outcome, AttributeMap output) {
    if (isPersistenceContext(session.getDefinition())) {
        final EntityManager em = (EntityManager) context.getConversationScope()
                .remove(session.getDefinition().getId() + "/" + PERSISTENCE_CONTEXT_ATTRIBUTE);
        Boolean commitStatus = session.getState().getAttributes().getBoolean("commit");
        if (Boolean.TRUE.equals(commitStatus)) {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    em.joinTransaction();
                }/*from  w  w w .j  a  va2s.c o m*/
            });
        }
        unbind(em);
        em.close();
    }
    if (!session.isRoot()) {
        FlowSession parent = session.getParent();
        if (isPersistenceContext(parent.getDefinition())) {
            bind(getEntityManager(context, parent.getDefinition().getId()));
        }
    }
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);/*from   www  . j  a  va2s . c o m*/
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}