You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Hibernate Criteria API中为MySQL保留关键字添加反引号?

解决Hibernate Criteria API处理MySQL保留关键字表名的问题

问题场景

我使用Hibernate Criteria API操作MySQL 8中名为Lead的表,该表名属于MySQL保留关键字。但Criteria API生成的SQL语句未给表名添加反引号,导致MySQL抛出语法错误。

期望生成的SQL语句

select * from `Lead` lead0_ where lead0_.isClosed=0 
order by lead0_.updatedAt desc limit 20

当前使用的Criteria API代码

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Lead> query = cb.createQuery(Lead.class);
Root<Lead> root = query.from(Lead.class);

Predicate[] predicates = new Predicate[1];
predicates[0] = cb.equal(root.get("isClosed"), false);
query.where(predicates);

query.orderBy(cb.desc(root.get("updatedAt")));

List<Lead> leads = entityManager.createQuery(query).setMaxResults(20).getResultList();

实际生成的错误SQL(无反引号)

select * from Lead lead0_ where lead0_.isClosed=0 
order by lead0_.updatedAt desc limit 20

已尝试但无效的方法

  • 用双引号包裹表名:
@Table(name = "\"Lead\"")
public class Lead {
}
  • 用反引号包裹表名:
@Table(name = "`Lead`")
public class Lead {
}

正确解决方案

方法1:全局配置Hibernate自动转义保留关键字

通过配置让Hibernate自动识别MySQL保留关键字,给所有数据库标识符(表名、列名)添加反引号,一劳永逸解决冲突:

Hibernate核心配置(hibernate.cfg.xml)

<property name="hibernate.globally_quoted_identifiers">true</property>

Spring Boot配置(application.properties)

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

Spring Boot配置(application.yml)

spring:
  jpa:
    properties:
      hibernate:
        globally_quoted_identifiers: true

方法2:针对单个实体修正表名配置(需配合正确方言)

之前的写法无效大概率是因为方言配置错误,先确保使用MySQL 8专属方言,再修正实体类注解:

  1. 配置MySQL 8方言:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
  1. 修改实体类的@Table注解:
@Table(name = "`Lead`")
public class Lead {
    // 实体字段定义
}

方法3:Criteria API中手动指定表名(不推荐)

如果不想修改配置或实体类,可在Criteria API中手动设置带反引号的表名,但该方式依赖Hibernate内部逻辑,版本迭代可能失效:

Root<Lead> root = query.from(Lead.class);
root.getModel().setName("`Lead`");

内容的提问来源于stack exchange,提问作者Vinu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:47:46