執行 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(...)
@Entity
@Table(name = "revert") // 表名小寫
public class Revert {
@Id Long id;
Long articlesId; // 欄位名駝峰
// ...
}
確認:
@Entitypersistence.xml 或 LocalContainerEntityManagerFactoryBean 掃描包含該類的包packagesToScan="com.example.entity"HQL 查詢**實體類名**,非資料表名:
// ❌ 錯誤:使用表名
from revert where articles_id = 2
// ✅ 正確:使用實體類名 (大小寫敏感)
from Revert where articlesId = 2
// ✅ 別名查詢
from Revert r where r.articlesId = 2
Revert.javapublic class RevertRevert.class
<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 對應資料庫欄位修改實體/映射後,必須重啟應用或重建 SessionFactory 使元資料生效。
DEBUG org.hibernate.cfg.Configuration 觀察實體掃描日誌sessionFactory.getMetamodel().entity(Revert.class) 不拋異常即註冊成功Revert、屬性名 articlesId 完全一致
@SpringBootApplication
@EntityScan("com.example.entity") // 確保掃描路徑正確
public class Application { ... }