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:fr.amapj.service.services.meslivraisons.MesLivraisonsService.java

/**
 * Indique si il y a au moins une livraison cette semaine
 * @param dto//from ww w .j a v  a2  s.c o  m
 * @return
 */
private boolean hasLivraison(EntityManager em, Date dateDebut, Date dateFin) {
    // On extrait toutes les livraisons sur l'intervalle 
    Query q = em.createQuery("select count(mcd.dateLiv) from ModeleContratDate mcd WHERE "
            + "mcd.dateLiv>=:deb AND " + "mcd.dateLiv<=:fin ");
    q.setParameter("deb", dateDebut, TemporalType.DATE);
    q.setParameter("fin", dateFin, TemporalType.DATE);

    return LongUtils.toInt(q.getSingleResult()) > 0;
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.VirtualTopicsITCase.java

/**
 * Test add./*from   w ww. j a va 2 s  .  c  o  m*/
 *
 * @throws Exception the exception
 */
@Test
public void testAdd() throws Exception {

    assertEquals("DB not empty", 0, countArticles());

    EntityManager em = emf.createEntityManager();

    String[] ids = new String[] { "128", "130", "131", "132", "256", "704" };

    // insert all items
    for (String id : ids) {
        // item should not be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(0, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // send content to jms broker
        template.sendBody("activemq:topic:VirtualTopic.Orders", content);

        // wait
        Thread.sleep(TimeOuts.LONG);

        // item should be inserted to db
        query = em.createQuery(
                new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    assertEquals("not all items are present", ids.length, countArticles());

    em.close();
}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public List<Tournament> getPage(int first, int rows, String sortBy, boolean ascending,
        Map<String, Object> filters) {

    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //        CriteriaBuilder cb = entityManagerfactory.getCriteriaBuilder();
    //        CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    //        Root<Tournament> tou = cq.from(Tournament.class);
    //        cb.para
    //        criteria.add(cb.equal(tou, tou))
    //        String queryString = "SELECT e FROM " + Tournament.class.getSimpleName();
    //        if (!filters.isEmpty()) {
    //            queryString += " WHERE ";
    //            for (Map.Entry<String, Object> entry : filters.entrySet()) {
    //                if ("id".equals(entry.getKey())) {
    //                    queryString += "e." + entry.getKey() + " = " + entry.getValue();
    //                } else {
    //                    queryString += "e." + entry.getKey() + " LIKE '" + entry.getValue() + "'";
    //                }
    //            }
    //        }//  w w  w . j a v  a  2  s. co  m
    //                " e WHERE e." + property + " = :value";
    //        return getEntityManager().createQuery(queryString).setParameter("value", value).getResultList();
    //        return null;
    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //
    //        for (Map.Entry<String, Object> filter : filters.entrySet()) {
    //            if ("id".equals(filter.getKey())) {
    //                criteria.add(Restrictions.eq("id", Long.parseLong(filter.getValue().toString())));
    //            } else {
    //                criteria.add(Restrictions.ilike(filter.getKey(), (String) filter.getValue(), MatchMode.START));
    //            }
    //        }
    //
    //        if (ascending) {
    //            criteria.addOrder(Order.asc(sortBy));
    //        } else {
    //            criteria.addOrder(Order.desc(sortBy));
    //        }
    //
    //        criteria.setFirstResult(first);
    //        criteria.setMaxResults(rows);
    //
    //        criteria.setResultTransformer(Transformers.aliasToBean(clazz));
    //        List<ENTITY> list = criteria.list();
    //
    //        return list;
    EntityManager em = getEntityManager();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    Root<Tournament> t = cq.from(Tournament.class);

    cq.select(t);

    TypedQuery<Tournament> tq = em.createQuery(cq);

    List<Tournament> tournaments = tq.getResultList();
    return tournaments;

}

From source file:net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper.java

/**
 * Find entities./*from w  w  w  .java2 s .co m*/
 * 
 * @param em
 *            the em
 * @param target
 *            the target
 * @param all
 *            the all
 * @param maxResults
 *            the max results
 * @param firstResult
 *            the first result
 * @return the list
 * @since 28/08/2014, 11:20:27 PM
 */
private List<Entity> findEntities(EntityManager em, Class<Entity> target, boolean all, int maxResults,
        int firstResult) {
    CriteriaQuery<Entity> cq = em.getCriteriaBuilder().createQuery(target);
    cq.select(cq.from(target));
    TypedQuery<Entity> q = em.createQuery(cq);
    if (!all) {
        q.setMaxResults(maxResults);
        q.setFirstResult(firstResult);
    }
    return q.getResultList();
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.CommandITCase.java

/**
 * Before test.//from  w  ww. j a  v  a  2  s.  c  o m
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.createQuery("DELETE FROM article").executeUpdate();
    tx.commit();
    em.close();
}

From source file:net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper.java

/**
 * Gets the quantity./*w ww .  ja va 2s  .  c  om*/
 * 
 * @param dbAccess
 *            the db access
 * @param target
 *            the target
 * @return the quantity
 * @since 28/08/2014, 11:20:27 PM
 */
public int getQuantity(EntityManager dbAccess, Class<Entity> target) {
    CriteriaQuery<Long> cq = dbAccess.getCriteriaBuilder().createQuery(Long.class);
    Root<Entity> rt = cq.from(target);
    cq.select(dbAccess.getCriteriaBuilder().count(rt));
    Query q = dbAccess.createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

From source file:edu.vt.middleware.gator.JpaConfigManager.java

/** {@inheritDoc}. */
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public ProjectConfig findProject(final String name) {
    final EntityManager em = getEntityManager();
    final String queryString = "SELECT p FROM ProjectConfig p WHERE p.name = :name";
    final Query query = em.createQuery(queryString);
    query.setParameter("name", name);
    logger.trace("Executing query " + queryString);
    logger.trace("Query params: name=" + name);
    try {/* w w w . j av  a 2  s  .  c  o  m*/
        final ProjectConfig project = (ProjectConfig) query.getSingleResult();
        loadFullProject(project);
        return project;
    } catch (NoResultException e) {
        return null;
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//*from w w  w  .j ava2s.co  m*/
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:com.haulmont.cuba.core.jmx.PersistenceManager.java

@Authenticated
@Override//w  w w. ja  v  a2s . c o m
public String jpqlExecuteUpdate(String queryString, boolean softDeletion) {
    try {
        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            em.setSoftDeletion(softDeletion);
            Query query = em.createQuery(queryString);
            int count = query.executeUpdate();
            tx.commit();

            return "Done: " + count + " entities affected, softDeletion=" + softDeletion;
        } finally {
            tx.end();
        }
    } catch (Throwable e) {
        log.error("jpqlExecuteUpdate error", e);
        return ExceptionUtils.getStackTrace(e);
    }
}

From source file:de.egore911.opengate.services.PilotService.java

@GET
@Path("/verify/{login}")
@Produces("text/html")
@Documentation("Verify a pilots email address. This URL is sent to the pilot after registration and is the final step to complete the registration. If the email could not be verified (e.g. duplicate verification) it will return a HTTP 400 (Bad Request).")
public Response getVerifyForm(@PathParam("login") String login,
        @QueryParam("verification") @Documentation("The random generated verification code sent by mail to the user") String verificationCode) {
    if (verificationCode == null || verificationCode.isEmpty()) {
        return Response.ok(
                "<html><head></head><body><form method=\"post\"><input type=\"verification\"></form></body></html>")
                .build();//from  ww  w .j  a v a  2 s.  c  om
    } else {
        EntityManager em = EntityManagerFilter.getEntityManager();
        try {
            Pilot pilot = (Pilot) em
                    .createQuery("select pilot from Pilot pilot " + "where pilot.login = :login "
                            + "and pilot.verificationCode = :verificationCode")
                    .setParameter("login", login).setParameter("verificationCode", verificationCode)
                    .getSingleResult();
            pilot.setVerificationCode(null);
            pilot.setModified(new Date());
            em.merge(pilot);
            return Response.ok("E-Mail adress has been verified. You can log into the game now.").build();
        } catch (NoResultException e) {
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
}