gpt4 book ai didi

java - @Enumerated @ElementCollection 的命名策略

转载 作者:行者123 更新时间:2023-12-01 04:11:21 25 4
gpt4 key购买 nike

在我的 Java 应用程序中,我使用枚举集合,如下所示:

@ElementCollection
@Enumerated(EnumType.ORDINAL)
protected Set<Tag> tags = new TreeSet<>();

但是,这个定义是在 @MappedSuperClass 中给出的,因此我无法在 @JoinTable 中定义 name,因为名称会在子项中发生冲突类。我的问题是默认的 hibernate 命名策略被忽略。例如,对于继承类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com