首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate HQL 查詢異常:Revert is not mapped 解決方案

     編輯:Java 相關知識

執行 HQL from Revert r where r.articles_id=2 拋出 QuerySyntaxException: Revert is not mapped,根因在於實體類未正確註冊或命名不匹配。

錯誤堆疊核心


org.hibernate.hql.ast.QuerySyntaxException: Revert is not mapped.
[from Revert r where r.articles_id= 2]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(...)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(...)

常見原因與解決

1. 實體類未加 @Entity 或未掃描


@Entity
@Table(name = "revert")  // 表名小寫
public class Revert {
    @Id Long id;
    Long articlesId;  // 欄位名駝峰
    // ...
}

確認:

  • 類上有 @Entity
  • persistence.xml 或 LocalContainerEntityManagerFactoryBean 掃描包含該類的包
  • Spring: packagesToScan="com.example.entity"

2. HQL 使用類名而非表名

HQL 查詢**實體類名**,非資料表名:


// ❌ 錯誤:使用表名
from revert where articles_id = 2

// ✅ 正確:使用實體類名 (大小寫敏感)
from Revert where articlesId = 2

// ✅ 別名查詢
from Revert r where r.articlesId = 2

3. 實體類名與檔案名不符

  • 檔案:Revert.java
  • 類名:public class Revert
  • 編譯輸出:Revert.class

4. 映射檔 (.hbm.xml) 配置錯誤


<class name="com.example.entity.Revert" table="revert">
    <id name="id" column="id">...</id>
    <property name="articlesId" column="articles_id"/>
</class>

檢查:

  • name 為全限定類名
  • table 為實際表名
  • 屬性名 articlesId 對應 Java 欄位,column 對應資料庫欄位

5. SessionFactory 未重建

修改實體/映射後,必須重啟應用或重建 SessionFactory 使元資料生效。

除錯步驟

  1. 啟動日誌檢查:DEBUG org.hibernate.cfg.Configuration 觀察實體掃描日誌
  2. 程式碼驗證:sessionFactory.getMetamodel().entity(Revert.class) 不拋異常即註冊成功
  3. HQL 大小寫:實體類名 Revert、屬性名 articlesId 完全一致

Spring Boot 自動配置檢查


@SpringBootApplication
@EntityScan("com.example.entity")  // 確保掃描路徑正確
public class Application { ... }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved