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.authentification.PasswordManager.java

/**
 * Retrouve l'utilisateur avec cet e-mail
 * Retourne null si non trouv ou autre problme
 *///from w  w w .j a v  a2s. c  om
private Utilisateur findUser(String email, EntityManager em) {
    if ((email == null) || email.equals("")) {
        return null;
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Utilisateur> cq = cb.createQuery(Utilisateur.class);
    Root<Utilisateur> root = cq.from(Utilisateur.class);

    // On ajoute la condition where 
    cq.where(cb.equal(root.get(Utilisateur.P.EMAIL.prop()), email));

    List<Utilisateur> us = em.createQuery(cq).getResultList();
    if (us.size() == 0) {
        return null;
    }

    if (us.size() > 1) {
        logger.warn("Il y a plusieurs utilisateurs avec l'adresse " + email);
        return null;
    }

    return us.get(0);
}

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

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

    long size = countArticles();

    EntityManager em = emf.createEntityManager();

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

    // insert all items
    for (String id : ids) {
        // item should not be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").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("jms:topic:BUS_OUT", content);

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

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

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

    // now check, that items are not insert twice if resend the same content
    for (String id : ids) {
        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
        // wait
        Thread.sleep(TimeOuts.LONG);

        // only one item should be present
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    em.close();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Widget> readWidgetMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;/*from  w  w w.  j  av  a2s .  co  m*/

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager
                .createQuery("SELECT a FROM Widget a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Widget a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Course> readCoursesMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;/*ww  w .  j a va  2s . co  m*/

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager
                .createQuery("SELECT a FROM Course a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Course a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

/**
 * Get the reference years/*from w  ww  . j a  va2  s .c o m*/
 * 
 * @param stocks
 *            stocks to get reference years for
 * @return loaded years. <b>Please note:</b> no stocks (<code>null</code> or empty array) will return an empty list!
 */
@SuppressWarnings("unchecked")
public List<Integer> getReferenceYears(IDataStockMetaData... stocks) {
    if (stocks == null || stocks.length == 0) {
        return new ArrayList<Integer>();
    }

    List<String> lstRdsIds = new ArrayList<String>();
    List<String> lstDsIds = new ArrayList<String>();
    for (IDataStockMetaData m : stocks) {
        if (m.isRoot()) {
            lstRdsIds.add(Long.toString(m.getId()));
        } else {
            lstDsIds.add(Long.toString(m.getId()));
        }
    }

    String join = "";
    final List<String> whereSmtnts = new ArrayList<String>();

    if (!lstRdsIds.isEmpty()) {
        whereSmtnts.add("p.rootDataStock.id in (" + this.join(lstRdsIds, ",") + ")");
    }
    if (!lstDsIds.isEmpty()) {
        join = " LEFT JOIN p.containingDataStocks ds";
        whereSmtnts.add("ds.id in (" + this.join(lstDsIds, ",") + ")");
    }

    EntityManager em = PersistenceUtil.getEntityManager();
    return em
            .createQuery("select distinct p.timeInformation.referenceYear from Process p" + join + " WHERE "
                    + StringUtils.join(whereSmtnts, " OR ") + " order by p.timeInformation.referenceYear asc")
            .getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<FIREAdapter> readFIREAdaptersMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;/* w  w  w.j a v a 2 s  .  c om*/

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(
                "SELECT a FROM FIREAdapter a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM FIREAdapter a ORDER BY a.id");

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

@SuppressWarnings("unchecked")
public List<Product> readProducts(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;/*from  ww w.ja v  a2s  . c o m*/

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager
                .createQuery("SELECT a FROM Product a WHERE a.category.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Product a ORDER BY a.id");

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static List<RunView> viewList(User user, String moduleResourceUri, Integer offset, Integer limit,
        String cloudServiceName) throws ConfigurationException, ValidationException {
    List<RunView> views = null;
    EntityManager em = PersistenceUtil.createEntityManager();
    try {//from   w w  w  . j  a  v  a 2s.com
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Run> critQuery = builder.createQuery(Run.class);
        Root<Run> rootQuery = critQuery.from(Run.class);
        critQuery.select(rootQuery);
        Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri,
                cloudServiceName);
        if (where != null) {
            critQuery.where(where);
        }
        critQuery.orderBy(builder.desc(rootQuery.get("startTime")));
        TypedQuery<Run> query = em.createQuery(critQuery);
        if (offset != null) {
            query.setFirstResult(offset);
        }
        query.setMaxResults((limit != null) ? limit : DEFAULT_LIMIT);
        List<Run> runs = query.getResultList();
        views = convertRunsToRunViews(runs);
    } finally {
        em.close();
    }
    return views;
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.ejbql.EJBQLFieldsReader.java

@SuppressWarnings("unchecked")
public Vector readFields() throws Exception {
    prepareQuery();//from   w w w .ja v a 2 s .  c  om

    Vector fields = new Vector();
    EntityManager em = null;
    Query query = null;
    setSingleClassName(null);
    try {

        IReportConnection conn = IReportManager.getInstance().getDefaultConnection();
        if (!(conn instanceof EJBQLConnection)) {
            throw new Exception("No EJBQL connection selected.");
        }

        em = ((EJBQLConnection) conn).getEntityManager();

        query = em.createQuery(queryString);

        for (Iterator iter = queryParameters.keySet().iterator(); iter.hasNext();) {
            String parameterName = (String) iter.next();
            query.setParameter(parameterName, queryParameters.get(parameterName));
        }

        query.setMaxResults(1);
        List list = query.getResultList();

        if (list.size() > 0) {
            Object obj = list.get(0);

            if (obj != null && obj.getClass().isArray()) {
                // Fields array...
                Object[] fiels_obj = (Object[]) obj;
                for (int i = 0; i < fiels_obj.length; ++i) {
                    fields.add(createField(fiels_obj[i], i));
                }
            } else {
                setSingleClassName(obj.getClass().getName());
                fields = getFields(obj);
            }
        }

        return fields;

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {

    }
}

From source file:streaming.StreamingTest.java

public void listeFilmsFrancais() {
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    List<Film> film = em.createQuery("SELECT f FROM Film f JOIN f.pays p WHERE p.nom = 'France'")
            .getResultList();/*  www. j  a v a  2  s.  c  om*/
    Assert.assertTrue(film.size() == 1L);
}