我有一个名为 LocationType
的实体(BaseEntity
是一个 @MappedSuperclass
):
@Entity
public class LocationType extends BaseEntity
为此实体生成的表名称是 location_type
。我了解默认的命名策略是这样工作的。
我不明白的是为什么我不能强制 Hibernate 使用文字名称,locationtype
。无论我做什么:
@Entity(name = "LocationType")
public class LocationType
或
@Entity
@Table(name = "LocationType")
public class LocationType
或
@Entity(name = "LocationType")
@Table(name = "LocationType")
public class LocationType
表名总是以location_type
结尾。 Hibernate 知道得更多!
如果我使用任何其他名称
@Entity(name = "wtf")
然后表名也变成了wtf
。
这是记录在案的行为吗?在我看来像是一个错误。
类似问题:Hibernate ignores @Table(name = "...") for extended classes - created tablenames are all lower case (不过,它指的是继承映射)。
最佳答案
在此处查看文档。
Implementing a NamingStrategy .
这是 org.hibernate.cfg.ImprovedNamingStrategy
的行为,它将大小写混合的名称转换为嵌入的下划线名称。 http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/cfg/ImprovedNamingStrategy.html .因此,如果您明确使用名称“EventLog”,它将转换为“event_log”。
如果您只想使用在 @Table
中明确指定的名称,您应该使用 org.hibernate.cfg.DefaultNamingStrategy
。默认情况下,当您实例化您的 org.hibernate.cfg.Configuration
对象时使用它
如果您想对所有表使用 ImprovedNamingStrategy
,除了那些明确指定名称的表,您可以使用下面的子类。 columnName 和 tableName 方法是在显式指定名称时调用的方法,此子类保留指定的名称不受干扰。
public class RespectfulImprovedNamingStrategy extends ImprovedNamingStrategy
{
@Override
public String columnName(String columnName)
{
return columnName;
}
@Override
public String tableName(String tableName)
{
return tableName;
}
@Override
public String classToTableName(String className) {
return addUnderscores( StringHelper.unqualify(className) );
}
}
更多引用链接。
关于java - Hibernate 不允许我使用实体类名作为表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526783/