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:streaming.test.StreamingTest.java

public void requete0() {
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    System.out.println("Requete 0");
    System.out.println(em.createQuery("SELECT g FROM Genre g").getResultList());

}

From source file:org.grails.datastore.mapping.jpa.JpaSession.java

/**
 * Deletes all objects matching the given criteria
 *
 * @param criteria The criteria//from   w  ww.  ja v  a 2s.  co  m
 * @return The total number of records deleted
 */
public int deleteAll(final QueryableCriteria criteria) {
    return jpaTemplate.execute(new JpaCallback<Integer>() {
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            JpaQueryBuilder builder = new JpaQueryBuilder(criteria);
            JpaQueryInfo jpaQueryInfo = builder.buildDelete();
            javax.persistence.Query query = em.createQuery(jpaQueryInfo.getQuery());
            List parameters = jpaQueryInfo.getParameters();
            if (parameters != null) {
                for (int i = 0, count = parameters.size(); i < count; i++) {
                    query.setParameter(i + 1, parameters.get(i));
                }
            }
            return query.executeUpdate();
        }
    });
}

From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java

@FXML
private void cmdUpdateSET(ActionEvent event) {
    Task taskUpdateSET = new Task<Void>() {
        @Override//from w  w w  .  j av a2  s  .c o m
        public Void call() {
            try {
                EntityManager entityManager = Utils.getInstance().getEntityManagerFactory()
                        .createEntityManager();
                entityManager.getTransaction().begin();
                String temp = "";
                Integer count = 0;
                entityManager.createQuery("delete from TblContribuyentes t").executeUpdate();
                for (Integer i = 0; i <= 9; i++) {
                    URL url = new URL(
                            "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc"
                                    + String.valueOf(i) + ".zip");
                    ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8);
                    zipStream.getNextEntry();

                    Scanner sc = new Scanner(zipStream, "UTF-8");

                    while (sc.hasNextLine()) {
                        String[] ruc = sc.nextLine().split("\\|");
                        temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2];
                        if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) {
                            TblContribuyentes c = new TblContribuyentes();
                            c.setRucSinDv(ruc[0]);
                            c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1]));
                            c.setDv(ruc[2]);
                            entityManager.persist(c);
                            updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i)
                                    + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count)
                                    + " de aprox. 850.000.");
                            count++;
                        } else {
                            updateMessage(temp);
                        }
                    }
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                }

                updateMessage("Lista de RUC actualizada...");
                return null;
            } catch (Exception ex) {
                App.showException(this.getClass().getName(), ex.getMessage(), ex);
            }
            return null;
        }
    };
    lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty());
    new Thread(taskUpdateSET).start();
}

From source file:corner.orm.gae.impl.PaginatedJapEntityService.java

License:asdf

public long count(final Class<?> persistClass, final Object conditions) {
    return (Long) this.template.execute(new JpaCallback() {
        @Override/* www . j av  a2  s.c om*/
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            Iterable con = typeCoercer.coerce(conditions, Iterable.class);
            final Iterator it = con == null ? null : con.iterator();
            final StringBuffer sb = buildConditionJPQL(persistClass, it);
            sb.insert(0, "select count(root) ");
            Query query = entityManager.createQuery(sb.toString());
            if (it != null) {
                int i = 0;
                while (it.hasNext()) {
                    query.setParameter(i++, it.next());
                }
            }
            return Long.parseLong(query.getSingleResult().toString());
        }
    });
}

From source file:org.grails.datastore.mapping.jpa.JpaSession.java

/**
 * Updates all objects matching the given criteria and property values
 *
 * @param criteria   The criteria//www .j a va  2s .  c om
 * @param properties The properties
 * @return The total number of records updated
 */
public int updateAll(final QueryableCriteria criteria, final Map<String, Object> properties) {
    return jpaTemplate.execute(new JpaCallback<Integer>() {
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            JpaQueryBuilder builder = new JpaQueryBuilder(criteria);
            JpaQueryInfo jpaQueryInfo = builder.buildUpdate(properties);
            javax.persistence.Query query = em.createQuery(jpaQueryInfo.getQuery());
            List parameters = jpaQueryInfo.getParameters();
            if (parameters != null) {
                for (int i = 0, count = parameters.size(); i < count; i++) {
                    query.setParameter(i + 1, parameters.get(i));
                }
            }
            return query.executeUpdate();
        }
    });
}

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

@POST
@Path("/login/{login}")
@Produces("application/json")
@Documentation("Allows a pilot to log in. This method is called by the client through the server. "
        + "It returns the ID of the user and it's ship data on success. "
        + "Otherwise HTTP 404 (Not Found) will be return, or an HTTP 500 (Internal "
        + "Server Error) in case of an internal error.")
public Response performLogin(@PathParam("login") String login, @FormParam("password") String password) {
    EntityManager em = EntityManagerFilter.getEntityManager();
    try {/*  w w  w.j  a  va2  s . co m*/
        String passwordHash = hashPassword(password);
        try {
            Pilot pilot = (Pilot) em
                    .createQuery("select pilot from Pilot pilot " + "where pilot.login = :login "
                            + "and pilot.passwordHash = :passwordHash")
                    .setParameter("login", login).setParameter("passwordHash", passwordHash).getSingleResult();
            if (pilot.getVerificationCode() != null && !pilot.getVerificationCode().isEmpty()) {
                return Response.status(Status.UNAUTHORIZED).build();
            }
            try {
                JSONObject jsonObject = new JSONObject();
                StatusHelper.ok(jsonObject);
                jsonObject.put("id", pilot.getKey().getId());
                // TODO properly wrap the vessel and its equipment/cargo
                jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
                return Response.ok(jsonObject.toString()).build();
            } catch (JSONException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        } catch (NoResultException e) {
            LOG.log(Level.FINER, e.getMessage(), e);
            return Response.status(Status.NOT_FOUND).build();
        }
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}

From source file:BO.UserHandler.java

public boolean login(VUser u) {

    EntityManager em;
    EntityManagerFactory emf;//from w ww.ja  v  a2s .co m
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {

        Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email");
        q.setParameter("email", u.getEmail());
        q.setMaxResults(1);
        q.getSingleResult();
        return true;
    } catch (NoResultException e) {
        em.getTransaction().begin();
        User userToInsert = new User(u.getEmail());
        em.persist(userToInsert);
        em.flush();
        em.getTransaction().commit();
        return true;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:dao.jpa.TestJpaDao.java

@Test
@Transactional//from   w  w w.j  a  va  2s.c  om
public void testCountCriteria() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);

    Root<Book> root = criteria.from(Book.class);
    Join<Book, Author> join = root.join("author");
    criteria.where(join.isNotNull());

    CriteriaQuery<Long> countCriteria = JpaUtils.countCriteria(em, criteria);
    Long result = em.createQuery(countCriteria).getSingleResult();
    log.debug("Count: " + result);
}

From source file:controllers.AuthController.java

@UnitOfWork
@FilterWith(CTCheck.class)
public Result login(Context context, Session session, User req) {
    EntityManager entitymanager = entitiyManagerProvider.get();
    CriteriaBuilder cb = entitymanager.getCriteriaBuilder();

    try {/*ww w.  j av  a 2  s.com*/
        CriteriaQuery<User> query = cb.createQuery(User.class);
        Root<User> a = query.from(User.class);
        query.where(cb.equal(a.get(User_.email), req.getEmail()),
                cb.equal(a.get(User_.password), req.getPassword()));
        User u = entitymanager.createQuery(query).getSingleResult();
        String token = SessionIdentifierGenerator.nextSessionId();
        context.addCookie(Cookie.builder("token", token).build());
        session.put("token", token);
        session.put("email", u.getEmail());
        session.put("id", String.valueOf(u.getId()));
        ninjaCache.set(token, u.getId());
        return Results.json().render(new RespAuth(u.getId(), token, u.getEmail()));
    } catch (Exception e) {
        e.printStackTrace();
        return Results.json().status(400).render(new JSendResp(400, e));
    }
}

From source file:BO.UserHandler.java

private User getUserByEmail(String email) {
    User tempUser;//from ww  w.  jav a 2  s  .c  o  m

    EntityManager em;
    EntityManagerFactory emf;

    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        tempUser = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email")
                .setParameter("email", email).getSingleResult();
        return tempUser;
    } catch (NoResultException e) {
        throw (e);
    } catch (Exception e) {
        throw (e);
    } finally {
        if (em != null) {
            em.close();
        }
        if (emf != null) {
            emf.close();
        }
    }
}