【问题标题】:Automatically Add a Prefix to Column Names for @Embeddable Classes自动为 @Embeddable 类的列名添加前缀
【发布时间】:2011-03-04 01:34:21
【问题描述】:

我正在开发一个项目,在该项目中我通过添加 Hibernate 注释来保留一些 POJO。我遇到的一个问题是这样的代码失败了,因为 Hibernate 尝试将 Time_T 中的子字段映射到同一列(即 startTime.secstopTime.sec 都尝试映射到列 sec ,导致错误)。

@Entity
public class ExampleClass
{
  @Id
  long eventId;

  Time_T startTime;
  Time_T stopTime;
}

@Embeddable
public class Time_T
{
  int sec;
  int nsec;
}

由于整个系统中会出现很多这样的情况,如果有一个选项可以自动为列名附加前缀(例如,使列为startTime_secstartTime_nsecstopTime_sec , stopTime_nsec),而不必在每个字段的基础上应用覆盖。 Hibernate 是否具有此功能,或者是否有任何其他合理的解决方法?

【问题讨论】:

标签: java hibernate orm


【解决方案1】:

尝试将属性hibernate.ejb.naming_strategy 设置为org.hibernate.cfg.DefaultComponentSafeNamingStrategy

【讨论】:

  • Hibernate 5 将命名策略拆分为隐式部分(当没有给出明确的列覆盖时)和物理部分,即使使用列注释显式定义,它也会覆盖任何命名。有一个默认的隐式命名策略可用,它为嵌入的类添加前缀:hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl 另请参阅 [hibernate 文档][1] 了解更多详细信息 [1]:docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/…
  • 如果我已经在使用自定义命名策略怎么办?是否有特定的方法可以用此策略中的方法覆盖?
  • @MattiasMartens 你可以通过提供你的实现并配置它来做到这一点。我必须在默认使用 SpringImplicitNamingStrategy 的 Spring Boot 上下文中执行此操作。这使我无法切换到ImplicitNamingStrategyComponentPathImpl,然后我将其分类并使用弹簧靴的实现覆盖public Identifier determineJoinTableName(ImplicitJoinTableNameSource source)
【解决方案2】:

解决问题的另一种方法是使用@AttributeOverrides 和@AttributeOverride 注解。在您的示例中,Time_T.sec 属性映射到 sec 列。你可以像这样映射 ExampleClass:

@Entity
public class ExampleClass {
    @Id
    long eventId;

    @AttributeOverrides(
        @AttributeOverride(name = "sec", column = @Column(name = "start_sec"))
    )
    Time_T startTime;
    Time_T stopTime;
}

结果映射为startTime.sec <=> start_secstopTime.sec <=> sec。当然,您可以使用注解为stopTipe.sec 列创建一个更有意义的名称。

【讨论】:

  • 这显然是我不想做的,因为在整个代码中可能有很多这种模式的实例。我不想在@AttributeOverrides 注释中添加数百次。
  • 很抱歉,我没有足够注意您的第一条消息。您明确表示不想手动覆盖这些字段。
【解决方案3】:

在我的 org.hibernate:hibernate-core:5.0.12.Final 和 org.springframework.boot:spring-boot-starter-data-jpa:1.5.2.RELEASE 的情况下,我必须在我的 application.properties 文件:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

【讨论】:

  • 我使用的是spring boot 2.5.4,如果你想保留_而不是camel-case,只有spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl就足够了
【解决方案4】:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多