开发者

Automatically Add a Prefix to Column Names for @Embeddable Classes

开发者 https://www.devze.com 2023-01-04 01:24 出处:网络
I am developing a project in which I am persisting some POJOs by adding Hibernate annotations. One problem I am running into is that code like this fails, as Hibernate tries to map the sub-fields with

I am developing a project in which I am persisting some POJOs by adding Hibernate annotations. One problem I am running into is that code like this fails, as Hibernate tries to map the sub-fields within the Time_T onto the same column (i.e. startTime.sec and stopTime.sec both try to map to the colum sec, causing an error).

@Entity
public class ExampleClass
{
  @Id
  long eventId;

  Time_T startTime;
  Time_T stopTime;
}

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

As there will be many occurrences like this throughout the system, it would be nice if there was an option to automatically append a prefix to the column name (e.g. make the columns be startTime_sec, startTime_nsec, stopTime_sec, stopTime_nsec), without having to apply overrides on a开发者_JS百科 per-field basis. Does Hibernate have this capability, or is there any other reasonable work-around?


Try setting the property hibernate.ejb.naming_strategy to org.hibernate.cfg.DefaultComponentSafeNamingStrategy


In my case with org.hibernate:hibernate-core:5.0.12.Final and org.springframework.boot:spring-boot-starter-data-jpa:1.5.2.RELEASE I had to do the following properties in my application.properties file:

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


Another way to solve the problem is by using @AttributeOverrides and @AttributeOverride annotations. In your example the Time_T.sec property is mapped to sec column. You could map ExampleClass like this:

@Entity
public class ExampleClass {
    @Id
    long eventId;

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

The result mapping is startTime.sec <=> start_sec and stopTime.sec <=> sec. Of course you could use annotations to create a more meaningful name for stopTipe.sec column.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消