HQL查询中出现Hibernate表未映射错误

我有一个使用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;

...

}

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

回答:

异常消息怎么说?它说:

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

确实,没有。你的映射类型称为Book。它映射到名为的表Books,但类型称为Book。在编写HQL(或JPQL)查询时,你使用类型的名称,而不是表。

因此,将查询更改为:

select count(*) from Book

虽然我认为可能需要

select count(b) from Book b

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

以上是 HQL查询中出现Hibernate表未映射错误 的全部内容, 来源链接: utcz.com/qa/399795.html

回到顶部