在我的Java应用程序中,我使用枚举集合,如下所示:
@ElementCollection
@Enumerated(EnumType.ORDINAL)
protected Set<Tag> tags = new TreeSet<>();
但是,此定义在
@MappedSuperClass
中给出,因此我不能在name
中定义@JoinTable
,因为名称将在子类中冲突。我的问题是默认的休眠命名策略被忽略了。例如,对于继承的类Event
而不是名称为event_tags
的表,hibernate尝试使用Event_tags
,而不是字段event_id
尝试使用Event_id
。在我看来,Hibernate完全忽略了命名策略,只使用实体名称而不进行任何更改。如何强制其使用默认命名策略?
最佳答案
似乎默认的命名策略无法处理这些问题,因此您需要实现自己的命名策略。例如:
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);
}
}
关于java - @Enumerated @ElementCollection的命名策略,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19884250/