JPA(休眠)和自定义表前缀

2022-09-04 05:04:35

是否可以覆盖 JPA/Hibernate 中的表名,以便为所有项目实体添加通用前缀?例如,能够在所有 JBPM 5 表前面加上“JBPM5_”前缀。

接受的答案示例:

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);
   }
}

答案 1

一次重命名所有表的一种方法是实现自己的命名策略(实现 )。org.hibernate.cfg.NamingStrategy

使用的命名策略在持久性中指定.xml

<property name="hibernate.ejb.naming_strategy"
          value="com.example.MyNamingStrategy" />

答案 2

使用命名策略我之前的答案应该准确地提供你需要的东西。

从上一个答案复制:

下面是一个命名策略示例,它为联接表构建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("_", "");

    }

}

推荐