Hibernate embeddables:找不到组件属性 [英] Hibernate embeddables: component property not found

查看:456
本文介绍了Hibernate embeddables:找不到组件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Hibernate中使用JPA @Embeddable 。实体和embeddable都有一个名为 id 的属性:

I'm trying to use JPA @Embeddables with Hibernate. The entity and the embeddable both have a property named id:

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

@Embeddable
public class B extends A {

}

@Entity
public class C extends A {
    B b;
}

这会引发 org.hibernate.MappingException:component找不到属性:id

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

I want to avoid using @AttributeOverrides. I thus tried to set spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultComponentSafeNamingStrategy (I'm using Spring Boot). This did not have any effect (same exception). I, however, suspect that the setting is beeing ignored because specifying a non-existing class doesn't raise an exception.

奇怪的是,即使使用这个变种

The strange thing is, even with this variant

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

我仍然得到同样的错误。

I still get the same error.

推荐答案

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

The naming strategy configuration has changed. The new way as per the Spring Boot documentation is this:

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

此外,你不能使用 @Id @Embeddable 中。因此,我为embeddables创建了一个单独的 @MappedSuperclass

Also, you must not use @Id within an @Embeddable. I thus created a seperate @MappedSuperclass for embeddables:

@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;
}

这样,表 C 有两列 id b_id 。缺点当然是 A E 引入了一些冗余。关于DRY方法的评论非常受欢迎。

This way, the table C has two columns id and b_id. The downside is of course that A and E introduce some redundency. Comments regarding a DRY approach to this are very welcome.

这篇关于Hibernate embeddables:找不到组件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆