HQL 查询中的休眠表未映射错误

我有一个使用Hibernate在数据库上进行CRUD操作的Web应用程序。我收到一个错误,说该表未映射。请参阅 Java 文件:

错误信息:

org.springframework.orm.hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:660)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
...
Caused by: org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
...

这是我的方法:DAO.java

public int getTotalBooks(){
    return DataAccessUtils.intResult(hibernateTemplate.find(
          "SELECT COUNT(*) FROM Books"));
}

Book.java:

@Entity
@Table(name="Books")
public class Book {

    @Id
    @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="title", nullable=false)
    private String title;
    ...
}

我应该如何修改它才能工作?


答案 1

异常消息显示:

Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]

Books未映射。也就是说,没有名为 的映射类型。Books

事实上,没有。映射的类型称为 。它被映射到一个名为 的表,但类型称为 。编写 HQL(或 JPQL)查询时,将使用类型的名称,而不是表。BookBooksBook

因此,将您的查询更改为:

select count(*) from Book

虽然我认为它可能需要

select count(b) from Book b

如果 HQL 不支持该表示法。*


答案 2

hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];

Hibernate试图说它不知道一个名为“Books”的实体。让我们看一下您的实体:

@javax.persistence.Entity
@javax.persistence.Table(name = "Books")
public class Book {

右。的名已重命名为“Books”,但实体名称仍为类名中的“Book”。如果要设置实体名称,则应改用批注的名称:Book@Entity

// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {

这将设置实体名称和表名称。


当我从文件迁移到使用Java注释来描述休眠字段时,相反的问题发生在我身上。我的旧XML文件有:Person.hbm.xml

<hibernate-mapping package="...">
    <class name="Person" table="persons" lazy="true">
       ...
</hibernate-mapping>

我的新实体有一个我需要设置表名称的实体。@Entity(name=...)

// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {
    ...

然后我看到的是HQL错误,例如:

QuerySyntaxException: Person is not mapped
     [SELECT id FROM Person WHERE id in (:ids)]

这样做的问题是实体名称也被重命名为。我应该使用以下命令设置表名:persons

// no name = here so the entity can be used as Person
@javax.persistence.Entity
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {

推荐