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:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

public Set getServiceProviders(boolean isAdmin, String spAbbrUrl) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
    User dbUser = null;//from w w w.  java2 s.c  om
    try {
        dbUser = (User) em.createQuery("from User u where " + "u.id = :userid")
                .setParameter("userid", user.getId()).getSingleResult();
    } catch (NoResultException nre) {
        log.error("No serviceprovider for user found.");
        throw new Exception("No serviceprovider for user found.");
    }
    Set organizationLayers = getValidLayers(dbUser, em, isAdmin, spAbbrUrl);

    Set serviceproviders = null;
    if (organizationLayers != null && !organizationLayers.isEmpty()) {

        serviceproviders = new HashSet();
        Iterator it = organizationLayers.iterator();

        while (it.hasNext()) {
            Layer layer = (Layer) it.next();
            ServiceProvider sp = layer.getServiceProvider();
            if (!serviceproviders.contains(sp)) {
                serviceproviders.add(sp);
            }
        }
    }

    return serviceproviders;
}

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

private long getDatasetsFromNonRootDsCount(IDataStockMetaData dataStock) {
    final String dsField = this.getDataStockField();

    StringBuilder sb = new StringBuilder("SELECT COUNT(b) FROM DataStock a LEFT JOIN a.").append(dsField)
            .append(" b WHERE a.id=:dsId");

    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em.createQuery(sb.toString());

    query.setParameter("dsId", dataStock.getId());

    Long resultCount = (Long) query.getSingleResult();

    return resultCount.longValue();
}

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

/**
 * Get data set by UUID string and version
 * /*from ww w . ja  v a2  s . co  m*/
 * @param uuid
 *            the UUID string
 * @param version
 *            the version of the method
 * @return data set for the specified UUID string/version, or <code>null</code> if none found
 */
@SuppressWarnings("unchecked")
public T getByUuidAndVersion(String uuid, DataSetVersion version) {
    try {
        EntityManager em = PersistenceUtil.getEntityManager();
        Query q = em.createQuery("select a from " + this.getJpaName()
                + " a where a.uuid.uuid=:uuid and a.version.majorVersion=:major and a.version.minorVersion=:minor and a.version.subMinorVersion=:subMinor");
        q.setParameter("uuid", uuid);
        q.setParameter("major", version.getMajorVersion());
        q.setParameter("minor", version.getMinorVersion());
        q.setParameter("subMinor", version.getSubMinorVersion());
        return (T) q.getSingleResult();
    } catch (NoResultException e) {
        // none found, so let's return null
        return null;
    }
}

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

public <T extends Serializable> List<T> findBy(CriteriaQuery<T> criteria) throws Exception {
    List<T> res = new ArrayList<T>();

    EntityManager em = getEntityManager();

    try {/*from  w w  w .  j  a v a2s .c o m*/
        res = em.createQuery(criteria).getResultList();

    } 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:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Get a the most recent data set of type T by UUID string
 * /*from w ww.jav  a2s. co m*/
 * @param uuid
 *            the UUID string
 * @return data set of type T for the specified UUID string, or <code>null</code> if none found
 */
@SuppressWarnings("unchecked")
public T getByUuid(String uuid) {
    try {
        EntityManager em = PersistenceUtil.getEntityManager();
        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> results = q.getResultList();
        if (results.size() > 0) {
            return results.get(0);
        } else {
            return null;
        }
    } catch (NoResultException e) {
        // none found, so let's return null
        return null;
    }
}

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

/**
 * Get all other versions of this data set
 * /*from  w w w  .  j a va 2 s . c  o m*/
 * @return version instances of all version numbers that are available for the uuid of this data set except the
 *         current one
 */
@SuppressWarnings("unchecked")
public List<T> getOtherVersions(T current) {
    if (current == null) {
        return null;
    }

    final String uuid = current.getUuidAsString();
    final DataSetVersion v = current.getVersion();

    if (uuid == null || v == null) {
        return null;
    }

    try {
        EntityManager em = PersistenceUtil.getEntityManager();
        Query q = em.createQuery("select a from " + this.getJpaName()
                + " a WHERE a.uuid.uuid=:uuid AND (a.version.majorVersion<>:major OR a.version.minorVersion<>:minor OR a.version.subMinorVersion<>:subMinor) ORDER BY a.version.majorVersion desc, a.version.minorVersion desc, a.version.subMinorVersion desc");

        q.setParameter("uuid", uuid);
        q.setParameter("major", v.getMajorVersion());
        q.setParameter("minor", v.getMinorVersion());
        q.setParameter("subMinor", v.getSubMinorVersion());

        return q.getResultList();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:elaborate.editor.model.orm.service.ProjectService.java

private Long getEntriesCount(long project_id, EntityManager entityManager) {
    Long entriesCount = (Long) entityManager//
            .createQuery("select count(*) from ProjectEntry"//
                    + " where project_id=:project_id"//
            )///*w  ww . j av a  2s . c o m*/
            .setParameter("project_id", project_id)//
            .getSingleResult();
    return entriesCount;
}

From source file:elaborate.editor.model.orm.service.ProjectService.java

private Long getFacsimileCount(long project_id, EntityManager entityManager) {
    Long facsimileCount = (Long) entityManager//
            .createQuery("select count(*) from"//
                    + " Facsimile where project_entry_id in"//
                    + " (select id from ProjectEntry where project_id=:project_id)"//
            )///*from w ww. j  a  va2s  .c  o  m*/
            .setParameter("project_id", project_id)//
            .getSingleResult();
    return facsimileCount;
}

From source file:elaborate.editor.model.orm.service.ProjectService.java

private Long getTranscriptionCount(long project_id, EntityManager entityManager) {
    Long transcriptionCount = (Long) entityManager//
            .createQuery("select count(*) from Transcription"//
                    + " where project_entry_id in"//
                    + " (select id from ProjectEntry where project_id=:project_id)"//
            )////w w  w. j  a  v a 2 s . com
            .setParameter("project_id", project_id)//
            .getSingleResult();
    return transcriptionCount;
}

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

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    try {/*from   w ww .  jav  a2 s  .  com*/
        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);
    }
}