是否可以覆盖JPA / Hibernate中的表名,以便为所有项目实体添加公共前缀?例如,能够通过“JBPM5_”前缀为所有JBPM 5表添加前缀。
接受答案的示例:
public class JBPM5NamingStrategy extends ImprovedNamingStrategy {
public String classToTableName(String className) {
return StringHelper.unqualify(className);
}
public String propertyToColumnName(String propertyName) {
return propertyName;
}
public String tableName(String tableName) {
return "JBPM5_" + tableName;
}
public String columnName(String columnName) {
return columnName;
}
public String propertyToTableName(String className, String propertyName) {
return "JBPM5_" + classToTableName(className) + '_'
+ propertyToColumnName(propertyName);
}
}
答案 0 :(得分:25)
一次重命名所有表的一种方法是实现自己的namingStrategy(org.hibernate.cfg.NamingStrategy
的实现)。
使用的NamingStrategy在persistence.xml中由
指定<property name="hibernate.ejb.naming_strategy"
value="com.example.MyNamingStrategy" />
答案 1 :(得分:21)
使用NamingStrategy。这个previous answer of mine应该提供您所需要的。
从上一个回答复制:
以下是NamingStrategy的示例 构建表单的表名 TYPE1_TYPE2用于连接表并添加一个 所有表的公共前缀:
public class CustomNamingStrategy extends ImprovedNamingStrategy {
private static final long serialVersionUID = 1L;
private static final String PREFIX = "PFX_";
@Override
public String classToTableName(final String className) {
return this.addPrefix(super.classToTableName(className));
}
@Override
public String collectionTableName(final String ownerEntity,
final String ownerEntityTable, final String associatedEntity,
final String associatedEntityTable, final String propertyName) {
return this.addPrefix(super.collectionTableName(ownerEntity,
ownerEntityTable, associatedEntity, associatedEntityTable,
propertyName));
}
@Override
public String logicalCollectionTableName(final String tableName,
final String ownerEntityTable, final String associatedEntityTable,
final String propertyName) {
return this.addPrefix(super.logicalCollectionTableName(tableName,
ownerEntityTable, associatedEntityTable, propertyName));
}
private String addPrefix(final String composedTableName) {
return PREFIX
+ composedTableName.toUpperCase().replace("_", "");
}
}
答案 2 :(得分:6)
在Hibernate 5中,您仍然必须自己实现此行为。但是,现在有了隐式和物理命名策略。
这是为表名加上Hibernate 5前缀的示例实现:
package my.app;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class PrefixPhysicalNamingStrategy extends PhysicalNamingStrategyStandardImpl {
/**
* TODO Make this an injectable application property
*/
public static final String TABLE_NAME_PREFIX = "MY_PREFIX_";
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
Identifier newIdentifier = new Identifier(TABLE_NAME_PREFIX + name.getText(), name.isQuoted());
return super.toPhysicalTableName(newIdentifier, context);
}
}
使用Spring Boot 2的此配置属性来激活您的物理命名策略:
spring.jpa.hibernate.naming.physical-strategy: my.app.PrefixPhysicalNamingStrategy