我在迁移到 Hibernate 5 时遇到了同样的问题,尽管我们有一个 Oracle 后端。通过同时使用org.hibernate.boot.model.naming.ImplicitNamingStrategy
和org.hibernate.boot.model.naming.PhysicalNamingStrategy
.
这是我的应用程序上下文中我的 bean 定义的样子:
@Bean
@Primary
public static JpaProperties jpaProperties() {
final Map<String, String> hibernateConfig = newHashMap();
hibernateConfig.put("hibernate.implicit_naming_strategy",
"org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl");
hibernateConfig.put("hibernate.physical_naming_strategy",
"com.anyapp.CustomNamingStrategy");
final JpaProperties jpaProperties = new JpaProperties();
jpaProperties.setProperties(hibernateConfig);
jpaProperties.setDatabase(ORACLE);
jpaProperties.setDatabasePlatform(ORACLE12C_DIALECT);
jpaProperties.setGenerateDdl(false);
jpaProperties.setShowSql(false);
return jpaProperties;
}
最烦人的部分是找出以何种方式应用哪些命名策略以及我必须自己实现的事实CustomNamingStrategy
,因为 Hibernate 不提供PhysicalNamingStrategy
与 legacy 的命名匹配的ImprovedNamingStrategy
。
以下是我的内容CustomNamingStrategy
:
package com.anyapp;
import org.apache.commons.lang.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class CustomNamingStrategy implements PhysicalNamingStrategy {
@Override
public Identifier toPhysicalCatalogName(Identifier identifier, JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalColumnName(Identifier identifier, JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSchemaName(Identifier identifier, JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalSequenceName(Identifier identifier, JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
@Override
public Identifier toPhysicalTableName(Identifier identifier, JdbcEnvironment jdbcEnv) {
return convert(identifier);
}
private Identifier convert(Identifier identifier) {
if (identifier == null || StringUtils.isBlank(identifier.getText())) {
return identifier;
}
String regex = "([a-z])([A-Z])";
String replacement = "$1_$2";
String newName = identifier.getText().replaceAll(regex, replacement).toLowerCase();
return Identifier.toIdentifier(newName);
}
}
您可能必须调整正则表达式以满足您的确切需求,但这对我有用。