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

Asked

Viewed 703 times

1

I am using the Eclipselink implementation and cannot solve the following query that must be wrong:

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

My entyties sane:

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 the query and also how to achieve the same result using the new features of the JPA 2.1 the famous Stored Procedure Query.

I already searched and found some examples that received a parameter for the function but in my case and I do not pass nor a parameter I just want the result!

Here is the link in English from the example, which receives a parameter in the stored procedure.

  • What mistake are you making? Try it this way: SELECT COUNT(*) FROM Empregado e

  • I tried that! It didn’t work, jpa doesn’t recognize the *

2 answers

1

  • Thanks for the attention.At this link, the guy isn’t using Spring Framework? Doesn’t that make a difference? I’m using Eclipseelink

  • 1

    @Penapintada As you are using JPA, Eclipselink will use JPQL syntax, and this Celso command is correct according to the Eclipselink wiki

  • @Julian! Thanks , but still , unfortunately ,I can’t get the result. The friend could not implement these two small classes and see if it works?

  • After implementing the Celso solution what error you receive?

0

In fact the type of return is not Integer and 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.