自动为@Embeddable类的列名添加前缀

Vee*_*Arr 30 java orm hibernate

我正在开发一个项目,我通过添加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;
}
Run Code Online (Sandbox Code Playgroud)

由于会有很多出现这样在整个系统中,这将是很好,如果有自动追加的前缀列的名称(例如使列是一个选项startTime_sec,startTime_nsec,stopTime_sec,stopTime_nsec),而不必基于每个应用覆盖现场基础.Hibernate是否具备此功能,还是有其他合理的解决方法?

Boz*_*zho 27

尝试将属性设置hibernate.ejb.naming_strategyorg.hibernate.cfg.DefaultComponentSafeNamingStrategy

  • Hibernate 5将命名策略拆分为隐式部分(当没有给出显式列覆盖时)和物理部分,即使用列注释明确定义,它也会覆盖任何命名.有一个默认的隐式命名策略,它为嵌入式类添加前缀:`hibernate.implicit_naming_strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl`另请参阅[hibernate documentation] [1]了解更多详细信息[1]:https: //docs.jboss.org/hibernate/orm/5.1/userguide/html_single/chapters/domain/naming.html (9认同)
  • 如果我已经在使用自定义命名策略,该怎么办?是否有特定方法可以用此策略中的方法覆盖? (2认同)

Far*_*jmi 11

在我的情况下使用org.hibernate:hibernate-core:5.0.12.Final和org.springframework.boot:spring-boot-starter-data-jpa:1.5.2.RELEASE我必须在我的应用程序中执行以下属性.属性文件:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Run Code Online (Sandbox Code Playgroud)

  • 我使用 spring boot 2.5.4,如果你想保留 _ 而不是驼峰式大小写,则仅 `spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl` 就足够了 (3认同)

Mat*_*ira 7

解决该问题的另一种方法是使用@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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这显然是我不想做的事情,因为在整个代码中可能存在许多这种模式的实例.我不想在`@ AttributeOverrides`注释中添加数百次. (3认同)
  • 对不起,我没有足够注意你的第一条消息。您明确表示您不想手动覆盖这些字段。 (2认同)