Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

In this page you can find the example usage for javax.persistence EntityManager createNamedQuery.

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends EntityBaseStandard> T findSingle(Class<T> classObj, String query, Map<String, Object> map)
        throws Exception {
    T returnValue = null;/*from   w w  w. ja  va 2  s.  c om*/

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Query q = null;
    Iterator i = null;
    Map.Entry entry = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        q = em.createNamedQuery(query);
        if (map != null) {
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        try {
            returnValue = (T) q.getSingleResult();
        } catch (NoResultException ex) {
            returnValue = null;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        i = null;
        entry = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends EntityBaseStandard> List<T> findList(Class<T> classObj, String query, Map<String, Object> map,
        int firstItem, int batchSize) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;/*w  ww  .  j  a  va2 s  .  co m*/
    EntityManager em = null;
    Query q = null;
    Iterator i = null;
    Map.Entry entry = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        q = em.createNamedQuery(query);
        if (batchSize > 0) {
            q.setFirstResult(firstItem);
            q.setMaxResults(batchSize);
        }
        if (map != null) {
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        returnValue = (List<T>) q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        i = null;
        entry = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * /* ww w .  j a v  a 2 s.  co m*/
 * Metodo che restituisce il numero di elementi dato un certo tipo, la query
 * e la mappa dei parametri
 * 
 * @param classObj
 * @return
 * @throws java.lang.Exception
 */
public int getItemCount2(Class<? extends EntityBaseStandard> classObj, String query, Map<String, Object> map)
        throws Exception {
    int returnValue = 0;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Creo la query */
        q = em.createNamedQuery(query);

        /* Verifico la validit della mappa dei parametri */
        if (map != null) {

            /* Per ogni elemento della mappo setto un parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }

        /* Calcolo il valore di ritorno */
        returnValue = ((Long) q.getSingleResult()).intValue();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * Metodo che restituisce l'oggetto cercato specificando la classe
 * dell'oggetto, la query di ricerca e la mappa dei parametri
 * /* w w  w  . ja  v  a  2  s .c o  m*/
 * @param classObj
 * @param query
 * @param map
 * @return EntityBase
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> T findSingle2(Class<T> classObj, String query, Map<String, Object> map)
        throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Creo la query */
        q = em.createNamedQuery(query);

        /* Verifico che la mappa dei parametri sia valida */
        if (map != null) {

            /* Per ogni oggetto della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }
        try {
            /* Lancio la query */
            returnValue = (T) q.getSingleResult();
        } catch (NoResultException ex) {
            /* Se non ci son risultati ritorno null */
            returnValue = null;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * /*from w w  w  .  ja v  a 2  s .co m*/
 * Metodo che restituisce una collezione di oggetti specificati come
 * parametro, tramite la query da lanciare, la mappa dei parametri,
 * l'elemento di inizio e il numero di elementi desiderati (mettendo a 0
 * questo parametro li restituisce tutti)
 * 
 * @param classObj
 * @param query
 * @param map
 * @param firstItem
 * @param batchSize
 * @return
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> List<T> findList2(Class<T> classObj, String query,
        Map<String, Object> map, int firstItem, int batchSize) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Genero la query */
        q = em.createNamedQuery(query);

        /*
         * Se il numero di elementi  diverso da 0 specifico quanti e da
         * dove cominciare
         */
        if (batchSize > 0) {
            q.setFirstResult(firstItem);
            q.setMaxResults(batchSize);
        }

        /* Verifico la validit della mappa */
        if (map != null) {
            /* Per ogni elemento della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }

        /* Calcolo la collezione di elementi desiderati */
        returnValue = (List<T>) q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:be.thomasmore.controller.FileController.java

private void leesExcel() {
    try {/*from   w ww. j  av a2  s  .  c o m*/
        //Excelbestand in RAM steken voor Apache POI
        InputStream fileInputStream = part.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet worksheet = workbook.getSheet("Blad1");
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ScoreTrackerPU");
        EntityManager em = emf.createEntityManager();
        //Iterator om door de worksheets te gaan (enkel nodig om het eerste worksheet door te gaan)
        Iterator<Row> rowIterator = worksheet.iterator();

        //Klas zoeken en persisten
        //Door de rijen itereren
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //Over de kolommen van deze rij itereren
            Iterator<Cell> cellIterator = row.cellIterator();
            if (row.getRowNum() == 0) {
                while (cellIterator.hasNext()) {
                    //Cell vastnemen
                    Cell cell = cellIterator.next();
                    //Kijken of er in de eerste cell 'klas' staat
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        if (cell.getStringCellValue().equalsIgnoreCase("klas")) {
                            //breaken zodat hij doorgaat naar de volgende cell
                            break;
                            //Checken of de cell niet leeg is
                        } else if (!cell.getStringCellValue().equalsIgnoreCase("")) {
                            if (klas.getNummer() == null) {
                                //Klas werkt
                                Query q = em.createNamedQuery("Klas.findByNummer");
                                q.setParameter("nummer", cell.getStringCellValue());
                                if (q.getResultList().size() == 0) {
                                    klas.setNummer(cell.getStringCellValue());
                                    defaultService.addKlas(klas);
                                } else {
                                    klas = (Klas) q.getSingleResult();
                                }
                            }
                        }
                        break;
                    }
                } //Einde van celliterator
            } else if (row.getRowNum() == 1) {
                while (cellIterator.hasNext()) {
                    //Cell vastnemen
                    Cell cell = cellIterator.next();
                    //Kijken of in de allereerste cel 'vak' staat
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        if (cell.getStringCellValue().equalsIgnoreCase("vak")) {
                            //breaken zodat hij doorgaat naar de volgende cell
                            break;
                        } else if (!cell.getStringCellValue().equalsIgnoreCase("")) {
                            if (vak.getNaam() == null) {
                                Query q = em.createNamedQuery("Vak.findByNaam");
                                q.setParameter("naam", cell.getStringCellValue());
                                if (q.getResultList().size() == 0) {
                                    vak.setNaam(cell.getStringCellValue());
                                    defaultService.addVak(vak);
                                } else {
                                    vak = (Vak) q.getSingleResult();
                                }
                            }
                        }
                    }
                } //Einde van celliterator
            } else if (row.getRowNum() == 2) {
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getColumnIndex() == 1) {
                        test.setBeschrijving(cell.getStringCellValue());
                    }
                }
            } else if (row.getRowNum() == 3) {
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING
                            && cell.getStringCellValue().equalsIgnoreCase("totaal")) {

                    }
                    if (cell.getColumnIndex() == 1) {
                        test.setTotaalScore((int) cell.getNumericCellValue());
                        test.setVakId(vak);
                        ///
                        Query q = em.createNamedQuery("Test.findByBeschrijving");
                        q.setParameter("beschrijving", test.getBeschrijving());
                        if (q.getResultList().size() == 0) {
                            defaultService.addTest(test);
                        } else {
                            test = (Test) q.getSingleResult();
                        }
                        ///

                        klasTest.setKlasId(klas);
                        klasTest.setTestId(test);
                        Query q2 = em.createNamedQuery("Klastest.findByKlasIdTestId");
                        q2.setParameter("klasId", klasTest.getKlasId());
                        q2.setParameter("testId", klasTest.getTestId());
                        if (q2.getResultList().size() == 0) {
                            if (klasTest.getKlasId().getId() != null) {

                                defaultService.addKlastest(klasTest);
                            }
                        } else {
                            klasTest = (Klastest) q2.getSingleResult();
                        }
                    }
                }
            } else if (row.getRowNum() > 5) {
                Student student = new Student();
                Score score = new Score();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    if (cell.getCellType() == Cell.CELL_TYPE_STRING
                            && cell.getStringCellValue().equalsIgnoreCase("zit al in de DB")) {
                        break;
                    }
                    if (cell.getColumnIndex() == 0) {
                        if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                            student.setStudentenNr((int) cell.getNumericCellValue());
                        }
                    }
                    if (cell.getColumnIndex() == 1) {
                        String[] voorenachternaam = cell.getStringCellValue().split("\\s+");
                        student.setVoornaam(voorenachternaam[0]);
                        if (voorenachternaam.length >= 3) {
                            if (voorenachternaam.length >= 4) {
                                student.setNaam(
                                        voorenachternaam[1] + voorenachternaam[2] + voorenachternaam[3]);
                                student.setEmail(voorenachternaam[0] + "." + voorenachternaam[1]
                                        + voorenachternaam[2] + voorenachternaam[3] + "@student.thomasmore.be");
                            } else {
                                student.setNaam(voorenachternaam[1] + voorenachternaam[2]);
                                student.setEmail(voorenachternaam[0] + "." + voorenachternaam[1]
                                        + voorenachternaam[2] + "@student.thomasmore.be");
                            }
                        } else {
                            student.setNaam(voorenachternaam[1]);
                            student.setEmail(
                                    voorenachternaam[0] + "." + voorenachternaam[1] + "@student.thomasmore.be");
                        }
                        student.setKlasId(klas);
                    }
                    if (cell.getColumnIndex() == 2) {
                        score.setScore((int) cell.getNumericCellValue());
                        score.setTestId(test);
                        score.setStudentId(student);
                        break;
                    }
                }

                if (student.getStudentenNr() != null) {
                    studenten.add(student);
                }
                if (score.getTestId() != null && score.getStudentId().getStudentenNr() != null) {
                    scores.add(score);
                }

            }
        } //einde van rowiterator
        for (Student student : studenten) {
            Query q = em.createNamedQuery("Student.findByStudentenNr");
            q.setParameter("studentenNr", student.getStudentenNr());
            if (q.getResultList().size() == 0) {
                defaultService.addStudent(student);
            } else {
                Student st = (Student) q.getSingleResult();
                student.setId(st.getId());
            }
        }
        for (Score score : scores) {
            Query q = em.createNamedQuery("Score.findByTestIdStudentIdScore");
            q.setParameter("testId", score.getTestId());
            q.setParameter("studentId", score.getStudentId());
            q.setParameter("score", score.getScore());
            if (q.getResultList().size() == 0) {
                defaultService.addScore(score);
            } else {
                score = (Score) q.getSingleResult();
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from   w w w .ja v a2  s .  c  o  m
public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) {
    FeedCategory fc = null;
    EntityManager em;
    EntityTransaction tx;
    User user;
    FeedData feedData;
    Feed f;
    boolean createdNewFD = false;

    if (data.getUrl() == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing"))
                .build();
    }

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    tx.begin();

    try {
        if (data.getCategoryId() != 0) {
            try {
                fc = (FeedCategory) em
                        .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class)
                        .setParameter("id", data.getCategoryId()).getSingleResult();
            } catch (NoResultException e) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity(new ErrorDescription("Feed category not found")).build();
            }

            if (!fc.getUser().equals(user)) {
                return Response.status(Response.Status.FORBIDDEN)
                        .entity(new ErrorDescription("Feed category not owned by user")).build();
            }
        }

        // Try to look up existing FeedData
        try {
            feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl())
                    .getSingleResult();
        } catch (NoResultException e) {
            feedData = new FeedData();
            feedData.setUrl(data.getUrl());

            try {
                loadFeedDetails(feedData);
            } catch (Exception ex) {
                e.printStackTrace();
                return Response.status(Response.Status.BAD_GATEWAY)
                        .entity(new ErrorDescription("Cannot fetch the feed")).build();
            }

            em.persist(feedData);
            createdNewFD = true;
        }

        f = new Feed();
        f.setUser(user);
        f.setFeedCategory(fc);
        f.setData(feedData);
        f.setName(feedData.getTitle());

        em.persist(f);

        tx.commit();

        if (createdNewFD)
            FeedsEngine.getInstance().submitFeedRefresh(feedData);

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:Logica.Usuario.java

@Override
public ArrayList<Integer> numerosDeOrdenRecibidas() throws RemoteException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU");
    EntityManager em = emf.createEntityManager();
    Query q = em.createNamedQuery("Recepcion.findAllOrdenes");
    List<Ordencompra> resultList = q.getResultList();
    ArrayList<Integer> numorden = new ArrayList<>();
    for (Ordencompra r : resultList) {
        numorden.add(r.getNumOrden().intValue());
    }//from   w  w w .j  a v a2  s .c  om
    return numorden;
}

From source file:Logica.Usuario.java

/**
 *
 * @return ArrayList//w w w  .  j av a 2s. c  o m
 * @throws RemoteException
 *
 * Genera una lista con todo el inventario existente en la base de datos
 */
@Override
public ArrayList<ItemInventario> itemInventarioAdmin() throws RemoteException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU");
    ArrayList<ItemInventario> lista = new ArrayList<>();
    EntityManager em = emf.createEntityManager();
    Query q = em.createNamedQuery("Item.InventarioAdmin");
    List<Item> resultList = q.getResultList();
    for (Item i : resultList) {
        lista.add(i.EntityToItem(i));
    }
    emf.close();
    return lista;
}

From source file:Logica.Usuario.java

/**
 *
 * @return ArrayList/*from  ww w.j  a v a2 s.c om*/
 * @throws RemoteException
 *
 * Genera una lista con todos los proveedores que se encuentran en el
 * sistema
 */
@Override
public ArrayList<proveedor> todosProveedores() throws RemoteException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU");
    ArrayList<proveedor> proveedores = new ArrayList<>();
    EntityManager em = emf.createEntityManager();
    Query q = em.createNamedQuery("Proveedor.findAllOrderByName");
    List<Proveedor> resultList = q.getResultList();
    for (Proveedor p : resultList) {
        proveedores.add(new proveedor(p.getNit(), p.getNombre(), p.getDir(), p.getTel(), p.getFax(),
                p.getCiudad(), p.getCelular(), p.getCorreo(), p.getContacto()));
    }
    emf.close();
    return proveedores;
}