SQL 带有复合主键查询的 JPA COUNT 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21733673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:02:08  来源:igfitidea点击:

JPA COUNT with composite primary key query not working

sqlhibernatejpacountcomposite-primary-key

提问by victorio

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.

我正在使用休眠。

回答by Sabuj Hassan

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.

使用count(d.ertek)count(d.id)代替count(d)。当您的实体具有复合主键时,就会发生这种情况。