自定义PhysicalNamingStrategy后Hibernate出现Table.getColumn返回空异常
场景与代码实现
编写JUnit测试验证仓库层时,使用H2数据库作为测试库。测试类代码如下:
PokemonRepositoryTest.java:
@DataJpaTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) @TestPropertySource(properties = { "spring.flyway.enabled=false", "spring.jpa.hibernate.naming.physical-strategy=com.example.j2.config.H2PhysicalNamingStrategy" }) public class PokemonRepositoryTest { @Autowired private PokemonRepository pokemonRepository; @Test public void saved_pokemon_is_not_null(){ // arrange Pokemon pokemon = Pokemon.builder() .name("pikachu") .type("electric") .build(); // act Pokemon saved = pokemonRepository.save(pokemon); // assert Assert.notNull(saved,"saved pokemon is null"); Assert.isTrue(saved.getId() > 0, "saved pokemon is not grater then 0"); } }
由于实体User对应的物理表名user是H2的保留关键字(未加引号时会转为大写USER),无法直接使用,因此实现了PhysicalNamingStrategy,为H2生成的所有表添加前缀(仅用于测试,开发环境用MySQL无此问题):
H2PhysicalNamingStrategy.java:
@Configuration public class H2PhysicalNamingStrategy implements PhysicalNamingStrategy { private static final String TABLE_PREFIX = "_"; @Override public Identifier toPhysicalCatalogName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return identifier; } @Override public Identifier toPhysicalSchemaName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return identifier; } @Override public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return Identifier.toIdentifier(TABLE_PREFIX + identifier.getText()); } @Override public Identifier toPhysicalSequenceName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return identifier; } @Override public Identifier toPhysicalColumnName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return identifier; } }
错误信息
运行测试时出现如下错误:
... Hibernate: drop table if exists _pokemon cascade Hibernate: drop table if exists _refresh_token cascade Hibernate: drop table if exists _review cascade Hibernate: drop table if exists _role cascade Hibernate: drop table if exists _user cascade Hibernate: drop table if exists _user_roles cascade Hibernate: create table _pokemon (id bigint generated by default as identity, name varchar(255), type varchar(255), primary key (id)) Hibernate: create table _refresh_token (id bigint generated by default as identity, user_id bigint, token varchar(255), primary key (id)) Hibernate: create table _review (stars integer, id bigint generated by default as identity, pokemon_id bigint, title varchar(255), content clob, primary key (id)) 2024-01-07T01:31:07.894+01:00 ERROR 132222 --- [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Error creating SQL 'create' commands for table '_role' [Cannot invoke "org.hibernate.mapping.Column.isUnique()" because the return value of "org.hibernate.mapping.Table.getColumn(org.hibernate.mapping.Column)" is null]
尝试修改后的情况
将前缀改为后缀,修改后的H2PhysicalNamingStrategy.java:
@Configuration public class H2PhysicalNamingStrategy implements PhysicalNamingStrategy { private static final String TABLE_SUFFIX = "_"; ... @Override public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { return Identifier.toIdentifier(identifier.getText() + TABLE_SUFFIX); } ... }
但仍出现相同错误:
... Hibernate: drop table if exists pokemon_ cascade Hibernate: drop table if exists refresh_token_ cascade Hibernate: drop table if exists review_ cascade Hibernate: drop table if exists role_ cascade Hibernate: drop table if exists user_ cascade Hibernate: drop table if exists user_roles_ cascade Hibernate: create table pokemon_ (id bigint generated by default as identity, name varchar(255), type varchar(255), primary key (id)) Hibernate: create table refresh_token_ (id bigint generated by default as identity, user_id bigint, token varchar(255), primary key (id)) Hibernate: create table review_ (stars integer, id bigint generated by default as identity, pokemon_id bigint, title varchar(255), content clob, primary key (id)) 2024-01-07T13:36:53.866+01:00 ERROR 3851 --- [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Error creating SQL 'create' commands for table 'role_' [Cannot invoke "org.hibernate.mapping.Column.isUnique()" because the return value of "org.hibernate.mapping.Table.getColumn(org.hibernate.mapping.Column)" is null]
错误原因
问题出在自定义的PhysicalNamingStrategy实现上:仅修改了表名,但未继承Hibernate默认的元数据处理逻辑,导致Hibernate在处理约束(如Role实体字段的唯一约束)时,内部元数据映射出现不匹配,无法找到对应列对象,从而抛出空指针相关的映射异常。
正确解决方案
方案1:全局启用Hibernate标识符引号转义
修改测试类的配置,让Hibernate为所有表名、列名添加引号,避免H2将保留关键字转为大写:
@TestPropertySource(properties = { "spring.flyway.enabled=false", "spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl", "spring.jpa.properties.hibernate.globally_quoted_identifiers=true" })
此方式无需自定义命名策略,直接通过配置解决保留关键字冲突。
方案2:为特定实体指定带引号的表名
仅针对User实体处理,在实体类上直接指定带引号的表名:
@Entity @Table(name = "\"user\"") public class User { // 实体字段... }
该方式只影响User实体,其他实体保持原有命名规则。
方案3:修复自定义命名策略实现
若坚持使用自定义命名策略,需继承Hibernate默认实现,保留原有元数据处理逻辑:
@Configuration public class H2PhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl { private static final String TABLE_SUFFIX = "_test"; @Override public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnvironment) { String newTableName = identifier.getText() + TABLE_SUFFIX; return Identifier.toIdentifier(newTableName, identifier.isQuoted()); } }
继承默认实现后,仅修改表名,不会破坏Hibernate内部的元数据关联,建议使用有意义的后缀(如_test)替代单个下划线,避免标识符命名不规范问题。
内容的提问来源于stack exchange,提问作者milanHrabos

