Iwnow Iwnow - 4 months ago 15
SQL Question

JPA, get all elements

I'm using JPA and I get all elements from DB in this code:

factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// read the existing entries and write to console
Query q = em.createQuery("select s from Supporter s");
List<Supporter> supportersList = new ArrayList<Supporter>();
supportersList = q.getResultList();


And the question is how to get data in more elegant way, I mean without
createQuery("select s from Supporter s");

As I remember there are somewhere methods like findAll or getAll to use in JPA when case is 'clear' and we don't need native queries.

Answer

You can use a type safe criteria:

public List<Supporter> findAll() {
    EntityManager em = factory.createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Supporter> cq = cb.createQuery(Supporter.class);
    Root<Supporter> rootEntry = cq.from(Supporter.class);
    CriteriaQuery<Supporter> all = cq.select(rootEntry);
    TypedQuery<Supporter> allQuery = em.createQuery(all);
    return allQuery.getResultList();
}