Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

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

Prototype

public Query createQuery(CriteriaDelete deleteQuery);

Source Link

Document

Create an instance of Query for executing a criteria delete query.

Usage

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

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
    EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
            .createEntityManager();//from w  ww  .  j  av a 2  s. c o  m
    entityManager.getTransaction().begin();
    int suma = 0;
    List<TblTransferencias> listT = (List<TblTransferencias>) entityManager
            .createQuery("select t from TblTransferencias t").getResultList();
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtAporte - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoAporte() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtAporte = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (sumAtDonacion - t.getTblAsientosTemporalesList().get(i).getMonto()
                            - t.getMontoDonacion() == 0) {
                        System.out.println(t.getTblAsientosTemporalesList().get(i).getId());
                        suma += t.getTblAsientosTemporalesList().get(i).getMonto();
                        t.getTblAsientosTemporalesList().get(i).setMonto(0);
                        sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
                        System.out.println(suma);
                        entityManager.merge(t);
                    }
                }
            }
        }

    }
    for (TblTransferencias t : listT) {
        Integer sumAtAporte = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(true)).mapToInt(l -> l.getMonto()).sum();
        Integer sumAtDonacion = t.getTblAsientosTemporalesList().stream()
                .filter(x -> x.getEsAporte().equals(false)).mapToInt(l -> l.getMonto()).sum();
        if (t.getMontoAporte() < sumAtAporte) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoAporte())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
        if (t.getMontoDonacion() < sumAtDonacion) {
            int asientoValido = -1;
            for (int i = 0; i < t.getTblAsientosTemporalesList().size(); i++) {
                if (!t.getTblAsientosTemporalesList().get(i).getEsAporte()) {
                    if (t.getTblAsientosTemporalesList().get(i).getMonto().equals(t.getMontoDonacion())) {
                        asientoValido = t.getTblAsientosTemporalesList().get(i).getId();
                        for (int ii = 0; ii < t.getTblAsientosTemporalesList().size(); ii++) {
                            if (!t.getTblAsientosTemporalesList().get(ii).getEsAporte()
                                    && t.getTblAsientosTemporalesList().get(ii).getId() != asientoValido) {
                                suma += t.getTblAsientosTemporalesList().get(ii).getMonto();
                                t.getTblAsientosTemporalesList().get(ii).setMonto(0);
                            }
                        }
                        entityManager.merge(t);
                    }
                }
            }
        }
    }
    entityManager.getTransaction().commit();
    entityManager.getTransaction().begin();
    JOptionPane.showMessageDialog(null, suma);
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public Device removeDevice(Device device) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        User user = getSessionUser();/*from   w  ww.  jav a 2  s  .  com*/
        entityManager.getTransaction().begin();
        try {
            device = entityManager.merge(device);
            user.getDevices().remove(device);
            device.setLatestPosition(null);
            entityManager.flush();
            Query query = entityManager.createQuery("DELETE FROM Position x WHERE x.device = :device");
            query.setParameter("device", device);
            query.executeUpdate();
            entityManager.remove(device);
            entityManager.getTransaction().commit();
            return device;
        } catch (RuntimeException e) {
            entityManager.getTransaction().rollback();
            throw e;
        }
    }
}

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  . j av  a  2s. c om
 * @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:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

protected Set getValidLayers(User user, EntityManager em, boolean isAdmin, String spAbbrUrl) throws Exception {

    Set organizationLayers = new HashSet();
    List layerlist = null;/*from  w  w  w.  j  ava 2s  .  c o m*/
    if (isAdmin) {
        if (spAbbrUrl == null) {
            layerlist = em.createQuery("from Layer l").getResultList();
        } else {
            layerlist = em.createQuery("from Layer l where l.serviceProvider.abbr = :spAbbr")
                    .setParameter("spAbbr", spAbbrUrl).getResultList();
        }
    } else {
        Set orgs = user.getAllOrganizations();

        if (spAbbrUrl == null) {
            layerlist = em
                    .createQuery("from Layer l where "
                            + "l in (select ol from Organization o join o.layers ol where o in (:orgs)) ")
                    .setParameter("orgs", orgs).getResultList();
        } else {
            layerlist = em
                    .createQuery("from Layer l where l.serviceProvider.abbr = :spAbbr and "
                            + "l in (select ol from Organization o join o.layers ol where o in (:orgs)) ")
                    .setParameter("spAbbr", spAbbrUrl).setParameter("orgs", orgs).getResultList();
        }

    }

    organizationLayers.addAll(layerlist);
    return organizationLayers;
}

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

public int executeUpdate(String query, Object... params) throws Exception {
    int res = 0;/*  w w  w  . j  a v  a 2  s  .c  o  m*/

    EntityManager em = getEntityManager();

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

        Query q = em.createQuery(query);

        if (params != null) {
            int i = 1;
            for (Object o : params) {
                q.setParameter(i, o);
                i++;
            }
        }

        res = q.executeUpdate();

        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();
        }
    }

    return res;
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected void initSiteProfiles(AdminMaintActionForm form, Site site) throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();

    Vector<LabelValueBean> vector = new Vector<LabelValueBean>();
    Long siteProfileClassDefaultId = null;
    SiteProfileClass siteProfileClassDefault = site.getSiteProfileClassDefault();
    if (siteProfileClassDefault != null) {
        siteProfileClassDefaultId = siteProfileClassDefault.getSiteProfileClassId();
        form.setSiteProfileClassDefaultId(siteProfileClassDefaultId);
        vector.add(new LabelValueBean(siteProfileClassDefault.getSiteProfileClassName(),
                siteProfileClassDefault.getSiteProfileClassId().toString()));
    }/*from www  . j a  va2 s  . c o  m*/

    String sql = "from   SiteProfileClass siteProfileClass " + "where  siteProfileClass.site.siteId = :siteId "
            + "order  by siteProfileClassName ";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfileClass siteProfileClass = (SiteProfileClass) iterator.next();
        if (siteProfileClassDefault != null) {
            if (siteProfileClass.getSiteProfileClassId().equals(siteProfileClassDefaultId)) {
                continue;
            }
        }
        vector.add(new LabelValueBean(siteProfileClass.getSiteProfileClassName(),
                siteProfileClass.getSiteProfileClassId().toString()));
    }
    LabelValueBean siteProfileClassBeans[] = new LabelValueBean[vector.size()];
    vector.copyInto(siteProfileClassBeans);
    form.setSiteProfileClassBeans(siteProfileClassBeans);

    if (form.getSiteProfileClassId() != null) {
        boolean found = false;
        for (LabelValueBean bean : siteProfileClassBeans) {
            if (bean.getValue().equals(form.getSiteProfileClassId().toString())) {
                found = true;
                break;
            }
        }
        if (!found) {
            form.setSiteProfileClassId(null);
        }
    }

    if (form.getSiteProfileClassId() == null) {
        if (siteProfileClassDefault != null) {
            form.setSiteProfileClassId(siteProfileClassDefaultId);
        }
        form.setSiteProfileClassDefault(true);
    } else {
        if (siteProfileClassDefault == null || form.getSiteProfileClassId().equals(siteProfileClassDefaultId)) {
            form.setSiteProfileClassDefault(true);
        } else {
            form.setSiteProfileClassDefault(false);
        }
        form.setTranslationEnable(false);
        String fromLocale = "";
        String toLocale = "";
        fromLocale = siteProfileClassDefault.getLanguage().getGoogleTranslateLocale();
        SiteProfileClass siteProfileClass = (SiteProfileClass) em.find(SiteProfileClass.class,
                form.getSiteProfileClassId());
        toLocale = siteProfileClass.getLanguage().getGoogleTranslateLocale();
        if (!Format.isNullOrEmpty(fromLocale) && !Format.isNullOrEmpty(toLocale)
                && !fromLocale.equals(toLocale)) {
            form.setTranslationEnable(true);
            form.setFromLocale(fromLocale);
            form.setToLocale(toLocale);
        }
    }

    vector = new Vector<LabelValueBean>();
    Long siteCurrencyClassDefaultId = null;
    SiteCurrencyClass siteCurrencyClassDefault = site.getSiteCurrencyClassDefault();
    if (siteCurrencyClassDefault != null) {
        siteCurrencyClassDefaultId = siteCurrencyClassDefault.getSiteCurrencyClassId();
        form.setSiteCurrencyClassDefaultId(siteCurrencyClassDefaultId);
        vector.add(new LabelValueBean(siteCurrencyClassDefault.getSiteCurrencyClassName(),
                siteCurrencyClassDefault.getSiteCurrencyClassId().toString()));
    }

    sql = "from   SiteCurrencyClass siteCurrencyClass " + "where  siteCurrencyClass.site.siteId = :siteId "
            + "order  by siteCurrencyClassName ";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrencyClass siteCurrencyClass = (SiteCurrencyClass) iterator.next();
        if (siteProfileClassDefault != null) {
            if (siteCurrencyClass.getSiteCurrencyClassId().equals(siteCurrencyClassDefaultId)) {
                continue;
            }
        }
        vector.add(new LabelValueBean(siteCurrencyClass.getSiteCurrencyClassName(),
                siteCurrencyClass.getSiteCurrencyClassId().toString()));
    }
    LabelValueBean siteCurrencyClassBeans[] = new LabelValueBean[vector.size()];
    vector.copyInto(siteCurrencyClassBeans);
    form.setSiteCurrencyClassBeans(siteCurrencyClassBeans);

    if (form.getSiteCurrencyClassId() == null) {
        if (siteCurrencyClassDefault != null) {
            form.setSiteCurrencyClassId(siteCurrencyClassDefaultId);
        }
        form.setSiteCurrencyClassDefault(true);
    } else {
        if (siteCurrencyClassDefault == null
                || form.getSiteCurrencyClassId().equals(siteCurrencyClassDefaultId)) {
            form.setSiteCurrencyClassDefault(true);
        } else {
            form.setSiteCurrencyClassDefault(false);
        }
    }
}

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

public <T extends Serializable> List<T> findBy(Class<T> clazz, JPAEntityFilter<T> filter) throws Exception {
    List<T> res = new ArrayList<T>();

    testClazz(clazz);/*from   w  w w  .j  av a  2  s  . c o  m*/

    EntityManager em = getEntityManager();

    try {

        if (filter != null) {
            CriteriaQuery<T> cq = filter.getCriteria(clazz, getEmf());
            TypedQuery<T> q = em.createQuery(cq);

            q.setFirstResult(filter.getLimit() * filter.getPageNumber());
            q.setMaxResults(filter.getLimit());

            res = q.getResultList();
        } else {
            res = findAll(clazz);
        }

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

    return res;
}