在我的Java应用程序中,我正在使用以下枚举:
@ElementCollection
@Enumerated(EnumType.ORDINAL)
protected Set<Tag> tags = new TreeSet<>();
然而,这个定义在@MappedSuperClass
中给出,因此我不能在name
中定义@JoinTable
,因为名称会在子类中发生冲突。我的问题是忽略了默认的hibernate命名策略。例如,对于继承的类Event
而不是名为event_tags
的表,hibernate尝试使用Event_tags
而不是字段event_id
,它尝试使用Event_id
}。在我看来,Hibernate完全忽略了命名策略,只是使用实体名称而没有任何改变。
如何强制它使用默认命名策略?
答案 0 :(得分:0)
似乎默认的命名策略无法处理这些,您需要实现自己的命名策略。例如:
public class NamingPolicy implements NamingStrategy, Serializable {
@Override
public String classToTableName(String className) {
return StringHelper.unqualify(className).toLowerCase();
}
@Override
public String propertyToColumnName(String propertyName) {
return StringHelper.unqualify(propertyName);
}
public String singularize(String propertyName) {
if (propertyName != null && propertyName.endsWith("s")) {
propertyName = propertyName.substring(0, propertyName.length() - 1);
}
return propertyName;
}
@Override
public String tableName(String tableName) {
return tableName;
}
@Override
public String columnName(String columnName) {
return columnName;
}
@Override
public String collectionTableName(
String ownerEntity, String ownerEntityTable, String associatedEntity,
String associatedEntityTable, String propertyName) {
return classToTableName(ownerEntityTable) + "_" +
or(associatedEntityTable, singularize(propertyName));
}
@Override
public String joinKeyColumnName(String joinedColumn, String joinedTable) {
return columnName(joinedColumn);
}
@Override
public String foreignKeyColumnName(
String propertyName, String propertyEntityName,
String propertyTableName, String referencedColumnName) {
String header = propertyName != null ? propertyName : propertyTableName;
if (header == null) {
throw new AssertionFailure("NamingStrategy not properly filled");
}
return classToTableName(header) + "_" + referencedColumnName;
}
@Override
public String logicalColumnName(String columnName, String propertyName) {
return StringHelper.isNotEmpty(columnName)
? columnName : StringHelper.unqualify(propertyName);
}
@Override
public String logicalCollectionTableName(
String tableName, String ownerEntityTable, String associatedEntityTable, String propertyName) {
if (tableName != null) {
return tableName;
} else {
return tableName(ownerEntityTable) + "_" + (associatedEntityTable != null
? associatedEntityTable
: singularize(propertyName));
}
}
@Override
public String logicalCollectionColumnName(
String columnName, String propertyName, String referencedColumn) {
return StringHelper.isNotEmpty(columnName)
? columnName
: classToTableName(propertyName) + "_" + singularize(referencedColumn);
}
}