JPA CriteriaQuery vs Iteración

I am wondering about the prefered way to handle where statements in JPA.

Hay dos maneras.

Either you use criteria query like

 CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Profile> c = cb.createQuery(Profile.class);
    Root<Profile> root = c.from(Profile.class);
    c.where(cb.equal(root.get(Profile_.email), email));
    List<Profile> resultList = em.createQuery(c).getResultList();

or you select the whole table and iterate in java like

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Profile> c = cb.createQuery(Profile.class);
//    Root<Profile> root = c.from(Profile.class);
//    c.where(cb.equal(root.get(Profile_.email), email));
    List<Profile> resultList = em.createQuery(c).getResultList();

    for (Profile profile : resultList) {
      if (profile.getEmail().equals(email)) {
        //todo
      }
    }

What is the prefered way and which pro and cons exists?

preguntado el 28 de mayo de 14 a las 12:05

Do consider the size of the table before deciding. It is always better to add a criteria when dealing with large tables. For Small tables either would do. -

1 Respuestas

The resulting select in the first case can be executed orders of magnitude faster than the filtering of instances in the second.

Databases are very fast and efficient in selection of data, so I am not aware of any downsides of the first approach.

The cons of the second method are tasks that do not need to be performed when using the first approach:

  • all objects in the table must be instantiated - depending on the number of records this can be prohibitively expensive, eventually bursting the memory limits of your VM.

  • all objects must be iterated, some methods invoked, comparisons made, unneeded instances garbage-collected - a waste of time and resources again.

contestado el 28 de mayo de 14 a las 17:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.