Spring Boot 2.1.6.RELEASE(Java 11)自定义表名替换失效,提示无效对象名称求助
Spring Boot 2.1.6.RELEASE(Java 11)自定义表名替换失效,提示无效对象名称求助
嘿,看你这情况是在 Spring Boot 2.1.6.RELEASE + Java 11 环境下,想通过 application.yml 里的配置来替换实体对应的数据库表名,还手写了 CustomPhysicalNamingStrategy 类,但现在应该是遇到表名替换没生效、数据库报「无效对象名称」的问题了对吧?
先把你贴出来的类代码放出来方便分析:
public class CustomPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl implements PhysicalNamingStrategy { private static Map<String, String> tableNames; public CustomPhysicalNamingStrategy(TableNamesProperties tableNamesProperties) { tableNames = new HashMap<>(); // 你这里是不是没把配置里的表名映射存到tableNames里? } }
接下来我给你捋几个最可能踩的坑,你逐一排查下:
- 代码逻辑不完整:你现在的构造函数只初始化了一个空的
HashMap,但完全没把TableNamesProperties里从application.yml读取到的表名映射放进去啊!比如你得加一行tableNames.putAll(tableNamesProperties.getMappings());(具体方法名看你TableNamesProperties里的定义,比如如果是用Map<String, String> mappings来接收配置,就用getMappings())。 - 核心方法没重写:你实现了
PhysicalNamingStrategy接口,但没重写关键的toPhysicalTableName方法啊!Hibernate 就是靠这个方法把实体的逻辑表名转换成物理表名的,你得加上:@Override public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) { // 从逻辑表名取对应的物理表名,没有的话就用原逻辑名 String physicalName = tableNames.getOrDefault(name.getText(), name.getText()); // 调用父类方法处理引号等规则 return super.toPhysicalTableName(new Identifier(physicalName, name.isQuoted()), context); } - 静态变量的坑:你把
tableNames定义成static了,这真的没必要!构造函数是注入实例的,静态变量会导致多个实例共享同一个映射,要是配置有变化或者多实例场景下绝对出问题,赶紧把static去掉,改成类的成员变量:private final Map<String, String> tableNames; public CustomPhysicalNamingStrategy(TableNamesProperties tableNamesProperties) { this.tableNames = new HashMap<>(tableNamesProperties.getMappings()); } - 配置没到位:
- 先确保
TableNamesProperties正确绑定application.yml的配置,比如给这个类加@ConfigurationProperties(prefix = "table-names")(前缀按你的配置来),然后在启动类上加@EnableConfigurationProperties(TableNamesProperties.class)让 Spring 能识别这个配置类。 - 还要在
application.yml里指定 Hibernate 用你的自定义命名策略:spring: jpa: hibernate: naming: physical-strategy: com.yourpackage.CustomPhysicalNamingStrategy
- 先确保
- 检查配置格式:
application.yml里的表名映射格式要对,比如:
这里的table-names: mappings: user: t_user order: t_orderuser是你实体类对应的逻辑表名(比如实体类是User,默认逻辑表名是user,或者你加了@Table(name = "user")就是这个值),对应到数据库的t_user。
你先按这些点检查一遍,尤其是重写 toPhysicalTableName 和把配置映射存到 tableNames 这两步,大概率是这俩没做好导致替换没生效的。
内容来源于stack exchange
相关产品推荐
相关产品推荐

