JPA COUNT with composite primary key query not working

victorio picture victorio · Feb 12, 2014 · Viewed 104.9k times · Source

In my db, I have a table (Defaults), and when I generate an entity from table, I get these two classes:

@Entity
public class Defaults implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected DefaultsPK DefaultsPK;
    @Column(name = "ERTEK")
    private String ertek;

    getter/setter...
}

@Embeddable
public class DefaultsPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "VALUE_1")
    private String value1;
    @Basic(optional = false)
    @Column(name = "TYPE")
    private String type;
    @Basic(optional = false)
    @Column(name = "VALID_FROM")
    @Temporal(TemporalType.TIMESTAMP)
    private Date validFrom;
    @Basic(optional = false)
    @Column(name = "VALID_TO")
    @Temporal(TemporalType.TIMESTAMP)
    private Date validTo;

    getter/setter...
}

That is why becaues the primary key is including the values. I want to count all the rows in the table, so I use this code:

String sql = "SELECT COUNT(d) FROM Defaults d";
Query q = em.createQuery(sql);
long count = (long)q.getSingleResult();

But I am getting this error:

org.hibernate.exception.SQLGrammarException: could not execute query
...
java.sql.SQLSyntaxErrorException: ORA-00907: The right expression is missing from the arithmetic expression

What is the problem? The other count queries with other entities are working.

I am using hibernate.

Answer

Sabuj Hassan picture Sabuj Hassan · Feb 12, 2014

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.