How to return the number of entities in a table using JPA and the COUNT function?

1

I'm using the EclipseLink implementation and I can not resolve the following query that should be wrong:

Query query = em.createQuery("SELECT e , COUNT(*) FROM Empregado e"); 
Integer resultado =  (Integer) query.getSingleResult();

My entyties is:

public class Empregado implements Serializable {
    @Id
    @GeneratedValue
    private int id;
    private String nome;
    private int idade;
    @OneToOne(cascade = CascadeType.ALL)
    private Telefone telefone;
    .... getters and setters

And this:

@Entity
public class Telefone {
    @Id
    @GeneratedValue
    private int id;    
    private String numero;
    private String tipo;
    .... getters and setters

The following error occurs:

  

Exception in thread "main" java.lang.IllegalArgumentException: An   exception occurred while creating a query in EntityManager:
      Exception Description: Syntax error parsing [SELECT e, COUNT (*) FROM Employee e].       [16, 16] The left expression is missing from the arithmetic expression.       [17, 17] The right expression is missing from the arithmetic expression

I would like to know if possible how to do query previous and also how to achieve the same result using the new features of JPA 2.1 the famous Stored Procedure Query .

I have already searched and found some examples that were given a parameter to the function but in my case and I do not even step one parameter I just want the result!

Here's the link in English of the example, which receives a parameter in the stored procedure.

    
asked by anonymous 10.08.2016 / 19:21

2 answers

1

Try this:

 "SELECT COUNT(e) FROM Empregados e"

Source: link

    
10.08.2016 / 19:34
0

Actually the return type is not Integer but yes Long
Here is the query:

String consulta = "SELECT COUNT(e) FROM Empregado e";
        TypedQuery<Long> query = em.createQuery(consulta, Long.class);
        Long resultado = query.getSingleResult();

        System.out.println(resultado);
    
10.08.2016 / 21:33