Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all records from table - EclipseLink

I've been trying to get all rows from table in EclipseLink.

I created my entities from db with the JPA tools. This is the result:

@Entity
@Table(name="employee", schema="hr")
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    public Employee() {
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

I found many pages where people create Query object to get all the records but they define again the "select" query like this.

Query q = em.createQuery("select e from Employee e");

But doing a research, finally I found something like this:

   public List<Employee> getEmployees() {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("ResourcesService");
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("from Employee e", Employee.class);
        return q.getResultList();
   }

Is there a even more simplified way to query this, just using the class name? Because the mapped entity already contains the select query.

I mean instead of doing this

   Query q = em.createQuery("from Employee e", Employee.class);

To do something like this fictional example:

   Query q = em.createQuery(Employee.class);
like image 458
Maximus Decimus Avatar asked Oct 18 '22 12:10

Maximus Decimus


1 Answers

Why not use the named query you have defined?

em.createNamedQuery("Employee.findAll").getResultList();

You could name it "Employee.class" ... :-)

like image 85
K.Nicholas Avatar answered Oct 21 '22 06:10

K.Nicholas