Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

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

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    try {//from www .ja va 2s  .co m
        CurrentUser currentUser = CurrentUser.getInstance();
        Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
        EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
                .createEntityManager();
        entityManager.getTransaction().begin();
        Query queryEventoDetalle = entityManager.createQuery("SELECT t FROM TblEventoDetalle t ORDER BY t.id");
        List<TblEventoDetalle> listEventoDetalle = org.jdesktop.observablecollections.ObservableCollections
                .observableList(queryEventoDetalle.getResultList());
        TblCuentasContablesPorDefecto cuentasContablesPorDefecto = entityManager
                .find(TblCuentasContablesPorDefecto.class, 1);
        for (TblEventoDetalle evd : listEventoDetalle) {
            if (evd.getTblAsientosList().size() == 2) {
                Integer indexAsientoAporte = -1;
                Integer indexAsientoDonacion = -1;
                if (((List<TblAsientos>) evd.getTblAsientosList()).get(0).getIdCuentaContableHaber()
                        .equals(cuentasContablesPorDefecto.getIdCuentaAportes())) {
                    indexAsientoAporte = 0;
                    indexAsientoDonacion = 1;
                } else if (((List<TblAsientos>) evd.getTblAsientosList()).get(1).getIdCuentaContableHaber()
                        .equals(cuentasContablesPorDefecto.getIdCuentaAportes())) {
                    indexAsientoAporte = 1;
                    indexAsientoDonacion = 0;
                }
                ((List<TblAsientos>) evd
                        .getTblAsientosList())
                                .get(indexAsientoAporte)
                                .setMonto(((Long) (evd.getMonto().longValue()
                                        * evd.getIdEvento().getPorcentajeAporte().longValue() / 100))
                                                .intValue());
                ((List<TblAsientos>) evd.getTblAsientosList()).get(indexAsientoDonacion).setMonto(evd.getMonto()
                        - ((List<TblAsientos>) evd.getTblAsientosList()).get(indexAsientoAporte).getMonto());
                entityManager.merge(evd);
            } else if (evd.getTblAsientosList().isEmpty()) {

                List<TblAsientos> ts = evd.getTblAsientosList();
                if (ts == null) {
                    ts = new LinkedList<>();
                    evd.setTblAsientosList((List) ts);
                }
                TblAsientos asientoAporte = new TblAsientos();
                asientoAporte.setFechahora(evd.getIdEvento().getFecha().atStartOfDay());
                asientoAporte.setIdCentroDeCostoDebe(evd.getIdEvento().getIdCentroDeCosto());
                asientoAporte.setIdCentroDeCostoHaber(evd.getIdEvento().getIdCentroDeCosto());
                asientoAporte.setIdCuentaContableDebe(cuentasContablesPorDefecto.getIdCuentaACobrar());
                asientoAporte.setIdCuentaContableHaber(cuentasContablesPorDefecto.getIdCuentaAportes());
                asientoAporte.setMonto(((Long) (evd.getMonto().longValue()
                        * evd.getIdEvento().getPorcentajeAporte().longValue() / 100)).intValue());
                asientoAporte.setIdUser(currentUser.getUser());

                ts.add(asientoAporte);

                TblAsientos asientoDonacion = new TblAsientos();
                asientoDonacion.setFechahora(evd.getIdEvento().getFecha().atStartOfDay());
                asientoDonacion.setIdCentroDeCostoDebe(evd.getIdEvento().getIdCentroDeCosto());
                asientoDonacion.setIdCentroDeCostoHaber(evd.getIdEvento().getIdCentroDeCosto());
                asientoDonacion.setIdCuentaContableDebe(cuentasContablesPorDefecto.getIdCuentaACobrar());
                asientoDonacion.setIdCuentaContableHaber(cuentasContablesPorDefecto.getIdCuentaDonaciones());
                asientoDonacion.setMonto(evd.getMonto() - asientoAporte.getMonto());
                asientoDonacion.setIdUser(currentUser.getUser());

                ts.add(asientoDonacion);

                entityManager.merge(evd);
            }
        }
        /*
        List<TblTransferencias> listT = (List<TblTransferencias>) entityManager.createQuery("select t from TblTransferencias t").getResultList();
        for (TblTransferencias t : listT) {
        Query queryEvd = entityManager.createQuery("select e from TblEventoDetalle e where e.idEvento.idEventoTipo = :eventoTipo and EXTRACT(MONTH FROM e.idEvento.fecha) = :mes and EXTRACT(YEAR FROM e.idEvento.fecha) = :ano and e.idEntidad = :entidad");
        Calendar c = Calendar.getInstance();
        c.setTime(t.getFechahora());
        queryEvd.setParameter("mes", c.get(Calendar.MONTH) + 1);
        queryEvd.setParameter("ano", c.get(Calendar.YEAR));
        queryEvd.setParameter("entidad", t.getIdEntidad());
        queryEvd.setParameter("eventoTipo", t.getIdEventoTipo());
                
        List<TblEventoDetalle> listEvd = queryEvd.getResultList();
        List<TblAsientos> listAsientos = new ArrayList<>();
        for (TblEventoDetalle evd : listEvd) {
            listAsientos.addAll(evd.getTblAsientosList());
        }
        List<TblAsientosTemporales> listAsientosTemporales = t.getTblAsientosTemporalesList();
        if (listAsientosTemporales == null) {
            listAsientosTemporales = new LinkedList<>();
            t.setTblAsientosTemporalesList(listAsientosTemporales);
        }
        if (t.getTblAsientosTemporalesList().isEmpty()) {
            for (TblAsientos asiento : listAsientos) {
                TblAsientosTemporales aT = new TblAsientosTemporales();
                entityManager.persist(aT);
                aT.setFacturado(false);
                aT.setFechahora(t.getFechahora());
                aT.setIdCentroDeCosto(asiento.getIdCentroDeCosto());
                aT.setIdCuentaContableDebe(asiento.getIdCentroDeCosto().getIdCuentaContableCtaCtePorDefecto());
                aT.setIdCuentaContableHaber(asiento.getIdCuentaContableDebe());
                if (asiento.getIdCuentaContableHaber().equals(cuentasContablesPorDefecto.getIdCuentaAportes())) {
                    aT.setEsAporte(true);
                } else {
                    aT.setEsAporte(false);
                }
                aT.setMonto(asiento.getMonto());
                listAsientosTemporales.add(aT);
            }
            entityManager.merge(t);
        }
        }*/
        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        JOptionPane.showMessageDialog(null, "Actualizacion satisfactoria!");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java

public Resolution save() {
    EntityManager em = Stripersist.getEntityManager();
    solrConfiguration.getIndexAttributes().clear();
    solrConfiguration.getResultAttributes().clear();
    for (int i = 0; i < indexAttributes.length; i++) {
        Long attributeId = indexAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getIndexAttributes().add(attribute);
    }/* w  w w. ja v a 2s . c  om*/

    for (int i = 0; i < resultAttributes.length; i++) {
        Long attributeId = resultAttributes[i];
        AttributeDescriptor attribute = em.find(AttributeDescriptor.class, attributeId);
        solrConfiguration.getResultAttributes().add(attribute);
    }
    em.persist(solrConfiguration);
    em.getTransaction().commit();

    return new ForwardResolution(EDIT_JSP);
}

From source file:it.attocchi.jpa2.JpaController.java

public void beginTransaction() {
    if (!globalTransactionOpen) {
        EntityManager em = getEntityManager();

        em.getTransaction().begin();

        globalTransactionOpen = true;//from  w  ww  . ja  v a2s.co m
    }
}

From source file:it.attocchi.jpa2.JpaController.java

public void commitTransaction() {
    if (globalTransactionOpen) {
        EntityManager em = getEntityManager();
        if (em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }//from ww  w.jav  a2  s  .  com
        globalTransactionOpen = false;
    }
}

From source file:it.attocchi.jpa2.JpaController.java

public void rollbackTransaction() {
    if (globalTransactionOpen) {
        EntityManager em = getEntityManager();
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }/* ww  w  .  j a  v a 2  s .c o m*/
        globalTransactionOpen = false;
    }

}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Set the {@link DataSet#setMostRecentVersion(boolean) most recent version flags} for all data sets with the
 * specified uuid. Please note that this method
 * <strong>does not open a separate transaction</strong>.
 * // w w w  . ja  v a 2  s .c  o m
 * @param uuid
 *            uuid of the data sets
 */
@SuppressWarnings("unchecked")
protected boolean setMostRecentVersionFlags(String uuid) {
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();
    try {
        Query q = em.createQuery("SELECT a FROM " + this.getJpaName()
                + " a WHERE a.uuid.uuid=:uuid ORDER BY a.version.majorVersion desc, a.version.minorVersion desc, a.version.subMinorVersion desc");
        q.setParameter("uuid", uuid);
        List<T> res = q.getResultList();
        if (!res.isEmpty()) {
            t.begin();
            // get first element and mark it as most recent version (correct order is taken care of in query!)
            T tmp = res.get(0);
            tmp.setMostRecentVersion(true);
            tmp = em.merge(tmp);

            // set "false" for all other elements if required
            final int size = res.size();
            if (size > 1) {
                for (int i = 1; i < size; i++) {
                    tmp = res.get(i);
                    if (tmp.isMostRecentVersion()) {
                        tmp.setMostRecentVersion(false);
                        tmp = em.merge(tmp);
                    }
                }
            }
            t.commit();
            return true;
        } else {
            DataSetDao.LOGGER.warn("Most recent version flag was called for non-existent UUID: " + uuid);
            return false;
        }
    } catch (Exception e) {
        DataSetDao.LOGGER.error("Could not set most recent version flag for UUID: " + uuid);
        if (t.isActive()) {
            t.rollback();
        }
        return false;
    }
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> void update(T o) throws Exception {

    EntityManager em = getEntityManager();

    try {/*from   www  . ja  v a  2 s .c o m*/
        if (!globalTransactionOpen)
            em.getTransaction().begin();
        em.merge(o);
        if (!globalTransactionOpen)
            em.getTransaction().commit();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> void insert(T o) throws Exception {

    EntityManager em = getEntityManager();

    try {// ww w .  j ava  2 s.  c o  m

        if (!globalTransactionOpen)
            em.getTransaction().begin();
        em.persist(o);
        if (!globalTransactionOpen)
            em.getTransaction().commit();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> void delete(Class<T> clazz, T o, Object id) throws Exception {

    testClazz(clazz);//from   ww w . j  a  va2s.  c om

    EntityManager em = getEntityManager();

    try {
        if (!globalTransactionOpen)
            em.getTransaction().begin();

        T attached = em.find(clazz, id);
        if (attached != null) {
            em.remove(attached);
            // em.remove(o);
        }
        if (!globalTransactionOpen)
            em.getTransaction().commit();

    } catch (Exception e) {
        throw e;
    } finally {

        // Close the database connection:
        if (!globalTransactionOpen) {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}