'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.



Solution 1:[1]

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();
}

Solution 2:[2]

To fetch all entries for a table,

@NamedQuery can also be used as follows

  1. Defining a named query annotation for a particular table.
@Entity
@NamedQuery(name="getallpeople", query="select p from People p")
public class People {
    //...
}
  1. Using a defined name query for a select query from the Repository class for your table

@Transactional
@Repository
public class PeopleRepository {

@PersistenceContext
    EntityManager entityManager;

public List<People> fetchAll() {

TypedQuery<Player> query1 = entityManager.createNamedQuery("getallpeople", People.class);

return query1.getResultList(); 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Diego Cortes
Solution 2 kaustubhd9