Hibernate embeddables:未找到组件属性

Eri*_*fer 7 java hibernate jpa spring-boot

我正在尝试将 JPA@Embeddable与 Hibernate一起使用。实体和可嵌入对象都有一个名为 的属性id

@MappedSuperclass
public abstract class A {
    @Id
    @GeneratedValue
    long id;
}

@Embeddable
public class B extends A {

}

@Entity
public class C extends A {
    B b;
}
Run Code Online (Sandbox Code Playgroud)

这引发了一个org.hibernate.MappingException: component property not found: id.

我想避免使用@AttributeOverrides. 因此我尝试设置spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultComponentSafeNamingStrategy(我使用的是 Spring Boot)。这没有任何影响(相同的例外)。但是,我怀疑该设置被忽略了,因为指定一个不存在的类不会引发异常。

奇怪的是,即使有这个变体

@Entity
public class C extends A {
    @Embedded
    @AttributeOverrides( {
        @AttributeOverride(name="id", column = @Column(name="b_id") ),
    } )
    B b;
}
Run Code Online (Sandbox Code Playgroud)

我仍然遇到同样的错误。

Eri*_*fer 9

命名策略配置已更改。根据Spring Boot 文档的新方法是这样的:

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

此外,您不得@Id@Embeddable. 因此,我@MappedSuperclass为可嵌入的对象创建了一个单独的对象:

@MappedSuperclass
public abstract class A {
    @Id
    @GeneratedValue
    long id;
}

@MappedSuperclass
public abstract class E {
    @GeneratedValue
    long id;
}

@Embeddable
public class B extends E {

}

@Entity
public class C extends A {
    B b;
}
Run Code Online (Sandbox Code Playgroud)

这样,该表C有两列idb_id。缺点当然是,AE引入了一些冗余。非常欢迎对 DRY 方法提出意见。