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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动为@Embeddable类的列名添加前缀相关的知识,希望对你有一定的参考价值。

我正在开发一个项目,我通过添加Hibernate注释来持久保存一些POJO。我遇到的一个问题是像这样的代码失败了,因为Hibernate试图将Time_T中的子字段映射到同一列(即startTime.secstopTime.sec都试图映射到colum 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_secstopTime_nsec),而不必应用覆盖,那将会很不错。在每个领域的基础上。 Hibernate是否具备此功能,还是有其他合理的解决方法?

答案

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

另一答案

在我的情况下使用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
另一答案

解决该问题的另一种方法是使用@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列创建更有意义的名称。

另一答案

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

以上是关于自动为@Embeddable类的列名添加前缀的主要内容,如果未能解决你的问题,请参考以下文章

使用带有 @Embeddable 类的 Spring Data 审计注释

对列名排序后转置和添加前缀的宏

在连接共享某些列名的两个表时,是不是有一种动态方法可以为一个表的所有列名添加前缀?

Oracle SQL - 为“create as select”添加重复的列名前缀

添加列名作为特定列的前缀

数据库设计时数据库名表名和列名大小写问题