[英]Automatically Add a Prefix to Column Names for @Embeddable Classes
I am developing a project in which I am persisting some POJOs by adding Hibernate annotations. 我正在开发一个项目,我通过添加Hibernate注释来持久保存一些POJO。 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 (ie startTime.sec
and stopTime.sec
both try to map to the colum sec
, causing an error). 我
Time_T
一个问题是像这样的代码失败,因为Hibernate试图将Time_T
的子字段Time_T
到同一列(即startTime.sec
和stopTime.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;
}
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 (eg make the columns be startTime_sec
, startTime_nsec
, stopTime_sec
, stopTime_nsec
), without having to apply overrides on a per-field basis. 由于在整个系统中会出现这样的情况,如果有一个选项可以自动为列名添加前缀(例如,使
startTime_sec
, startTime_nsec
, stopTime_sec
, stopTime_nsec
),而不必应用覆盖,那就太好了。在每个领域的基础上。 Does Hibernate have this capability, or is there any other reasonable work-around? Hibernate是否具备此功能,还是有其他合理的解决方法?
尝试将属性hibernate.ejb.naming_strategy
设置为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: 在我的情况下使用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
Another way to solve the problem is by using @AttributeOverrides and @AttributeOverride annotations. 解决该问题的另一种方法是使用@AttributeOverrides和@AttributeOverride注释。 In your example the
Time_T.sec
property is mapped to sec
column. 在您的示例中,
Time_T.sec
属性映射到sec
列。 You could map ExampleClass like this: 您可以像这样映射ExampleClass:
@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
. 结果映射是
startTime.sec <=> start_sec
和stopTime.sec <=> sec
。 Of course you could use annotations to create a more meaningful name for stopTipe.sec
column. 当然,您可以使用注释为
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.