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

如何在JPA 3 / Hibernate 6中获取实体的表名与模式名?

在Hibernate 6/JPA 3中获取实体对应的表名与模式名

你提到的两种基于getDescriptor()的方法在Hibernate 6中已被废弃,以下是两种基于Hibernate 6公开API的可行方案,无需依赖内部实现类,兼容性更好:

方案一:通过Hibernate Session直接获取

利用Hibernate Session工厂的元模型API获取实体映射信息:

// 从EntityManager解包得到Hibernate Session
var session = entityManager.unwrap(Session.class);
// 获取Hibernate的映射元模型
MappingMetamodel mappingMetamodel = session.getFactory().getRuntimeMetamodels().getMappingMetamodel();
// 获取对应实体的映射类型
EntityMappingType<?> entityMappingType = mappingMetamodel.getEntityDescriptor(Person.class);

// 获取主表表名
String tableName = entityMappingType.getPrimaryTable().getTableName();
// 获取模式名(实体未指定则返回默认值)
String schemaName = entityMappingType.getPrimaryTable().getSchemaName();
// 若需要获取catalog名,可使用以下方法
String catalogName = entityMappingType.getPrimaryTable().getCatalogName();

方案二:基于JPA元模型扩展获取

如果希望尽量贴合JPA规范,可通过JPA的EntityType转换为Hibernate的扩展接口:

// 获取JPA标准的实体元模型
EntityType<Person> jpaEntityType = entityManager.getMetamodel().entity(Person.class);
// 转换为Hibernate的EntityMappingType接口
EntityMappingType<Person> entityMappingType = jpaEntityType.unwrap(EntityMappingType.class);

// 获取表名与模式名
String tableName = entityMappingType.getPrimaryTable().getTableName();
String schemaName = entityMappingType.getPrimaryTable().getSchemaName();

补充说明

  • 以上方法均基于Hibernate 6的公开API,不会像之前依赖内部类的方案那样在版本更新中失效;
  • 如果实体通过@Table注解指定了name、schema或catalog,方法会返回注解配置的值;未指定时则返回Hibernate默认生成的名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:00:55