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.easyjf.core.dao.impl.GenericDAOImpl.java

public List query(final String queryStr, final Object[] params, final int begin, final int max) {
    List ret = (List) this.getJpaTemplate().execute(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query query = em.createQuery(queryStr);
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }/*from w  w  w . j  a  va2 s.  c  o m*/
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList();
    }
}

From source file:fr.amapj.service.services.saisiepermanence.PermanenceService.java

/**
 * //w  w w.  jav  a  2  s .co  m
 */
public List<PermanenceDTO> getAllDistributions(EntityManager em, Date dateDebut, Date dateFin) {
    Query q = em.createQuery("select d from DatePermanence d WHERE " + "d.datePermanence>=:deb AND "
            + "d.datePermanence<=:fin " + "order by d.datePermanence, d.id");
    q.setParameter("deb", dateDebut, TemporalType.DATE);
    q.setParameter("fin", dateFin, TemporalType.DATE);

    List<DatePermanence> dds = q.getResultList();
    List<PermanenceDTO> res = new ArrayList<PermanenceDTO>();

    for (DatePermanence dd : dds) {
        PermanenceDTO dto = createDistributionDTO(em, dd);
        res.add(dto);
    }

    return res;
}

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

@SuppressWarnings("unchecked")
public List<Long> getGroupIds(List<Organization> orgs) {
    if (orgs == null || orgs.isEmpty()) {
        return null;
    }//  ww w.  j  a  va2 s .c  o  m
    EntityManager em = PersistenceUtil.getEntityManager();

    List<Long> orgIds = new ArrayList<Long>();
    for (Organization o : orgs) {
        orgIds.add(o.getId());
    }

    try {
        return (List<Long>) em.createQuery("SELECT DISTINCT g.id FROM UserGroup g WHERE g.organization.id IN("
                + StringUtils.join(orgIds, ',') + ")").getResultList();
    } catch (Exception e) {
        return null;
    }
}

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

@GET
@Path("/list")
@Produces("application/json")
@Documentation("Returns a JSON array of available gameserver addresses (e.g. ['1.2.3.4', '4.5.6.7']). Only servers that called the 'add'-method within the last 15 minutes will be returned.")
public Response listGameservers() {
    EntityManager em = EntityManagerFilter.getEntityManager();
    JSONArray retval = new JSONArray();
    Calendar lastFifteenMinutes = Calendar.getInstance();
    lastFifteenMinutes.add(Calendar.MINUTE, -15);
    List<Gameserver> gameservers = em
            .createQuery("select gameserver from Gameserver gameserver where lastSeen > :lastSeen")
            .setParameter("lastSeen", lastFifteenMinutes.getTime()).getResultList();
    for (Gameserver gameserver : gameservers) {
        retval.put(gameserver.getAddress());
    }/*from ww  w  .j  a  v a2 s .co m*/
    return Response.ok(retval.toString()).build();
}

From source file:edu.csueb.cs6320.utils.UserService.java

/**
 * If the email/password combination is valid, returns the user that belongs to it; otherwise returns null
 * @param email      The user's email//from  w  w w .  ja  v  a2  s. com
 * @param password   The user's password
 * @return         The user, if authentic; otherwise null
 */
public User getAuthenticatedUser(String email, String password) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();

    User u = null;
    try {
        u = (User) em.createQuery("SELECT u FROM User u WHERE u.email = :inEmail")
                .setParameter("inEmail", email).setMaxResults(1).getSingleResult();
    } catch (javax.persistence.NoResultException e) {
        System.out.println("No user found with that email");
        return null;
    } catch (Exception e) {
        System.out.println("Exception occurred while trying to find user " + "by email address, of class: "
                + e.getClass().toGenericString());
        e.printStackTrace();
    }

    if (u == null) {
        return null;
    }

    try {
        if (Auth.isCorrectPassword(password, u.getSalt(), u.getSaltedHashedPassword())) {
            return u;
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:eu.optimis.trustedinstance.DBStorage.java

@SuppressWarnings("finally")
public boolean delete(String resourceKey) throws Exception {

    boolean result = true;
    EntityManager em = emf.createEntityManager();

    try {/*from   w  ww  .ja v a2  s .  c  o m*/
        String jpql = "delete from DBStorageEntry se where se.key=\"" + resourceKey + "\"";
        em.getTransaction().begin();
        Query query = em.createQuery(jpql);
        int row = query.executeUpdate();
        em.getTransaction().commit();
        if (row == 0) {
            result = false;
        }
    } catch (Exception e) {
        result = false;
        throw e;
    } finally {
        em.close();
        return result;
    }
}

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

/**
 * Count articles.//from  ww w .  j  ava2 s. c o m
 *
 * @return the long
 * @throws Exception the exception
 */
private long countArticles() throws Exception {
    EntityManager em = emf.createEntityManager();
    Query query = em.createQuery("SELECT COUNT(p.title) FROM article p");
    Long countResult = (Long) query.getSingleResult();

    em.close();

    return countResult;
}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public Long getCount(Map<String, Object> filters) {

    EntityManager em = getEntityManager();

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

    cq.select(cb.count(t));//from  w  w  w  .j a va 2s.c  o  m

    TypedQuery<Long> tq = em.createQuery(cq);
    return tq.getSingleResult();
}

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

@GET
@Path("/remove")
@Produces("application/json")
@Documentation("This method removes a gameserver from the list. It is recommend to call this "
        + "method on shutdown of the gameserver. The remote IP will be obtained from the packet "
        + "sent to the server so server behind a NAT will not work. The method will answer using "
        + "a JSON object like {status: 'ok', detail: '...'}.")
public Response removeGameserver(@Context HttpServletRequest req) {
    String remoteAddr = req.getRemoteAddr();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Gameserver gameserver;//from  www  .j a  v  a2s  .  c o  m
    try {
        JSONObject retval = new JSONObject();
        StatusHelper.ok(retval);
        try {
            gameserver = (Gameserver) em
                    .createQuery("select gameserver from Gameserver gameserver where address = :address")
                    .setParameter("address", remoteAddr).getSingleResult();
            em.remove(gameserver);
            retval.put("detail", "Successfully removed");
        } catch (NoResultException e) {
            // Nothing to do
            retval.put("detail", "Already removed");
        }
        return Response.ok(retval.toString()).build();
    } catch (JSONException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

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

@GET
@Path("/add")
@Produces("application/json")
@Documentation("Add or update a gameserver to the list of available game servers. "
        + "The remote IP will be obtained from the packet sent to the server so server "
        + "behind a NAT will not work. The method will answer using a JSON object like "
        + "{status: 'ok', detail: '...'}.")
public Response addGameserver(@Context HttpServletRequest req) {
    String remoteAddr = req.getRemoteAddr();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Gameserver gameserver;//  w  ww . j  av  a2 s .c o  m
    try {
        JSONObject retval = new JSONObject();
        StatusHelper.ok(retval);
        try {
            gameserver = (Gameserver) em
                    .createQuery("select gameserver from Gameserver gameserver where address = :address")
                    .setParameter("address", remoteAddr).getSingleResult();
            retval.put("detail", "Gameserver updated");
        } catch (NoResultException e) {
            gameserver = new Gameserver();
            gameserver.setAddress(remoteAddr);
            retval.put("detail", "Gameserver added");
        }
        gameserver.setLastSeen(new Date());
        em.persist(gameserver);
        return Response.ok(retval.toString()).build();
    } catch (JSONException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}