@Embeddable 和@ManyToOne

@Embeddable with @ManyToOne

想象一下类

@Embeddable
class A {
    @ManyToOne
    public B classB;

    ...
    public State someEnum;
}

@Entity
@Table(name = "TEST")
class B {
    public long id;
    //... some data


   @Embedded
   @AttributeOverrides({
        @AttributeOverride(
                name = "classB.id",
                column = @Column(name = "EMBEDDED1_ID")
        ),
        @AttributeOverride(
                name = "someEnum",
                column = @Column(name = "EMBEDDED1_SOMEENUM")
        )
   })
   public A embedded1;

   @Embedded
   @AttributeOverrides({
        @AttributeOverride(
                name = "classB.id",
                column = @Column(name = "EMBEDDED2_ID")
        ),
        @AttributeOverride(
                name = "someEnum",
                column = @Column(name = "EMBEDDED2_SOMEENUM")
        )
   })
   public A embedded2;
}

所以我希望数据库 table 看起来像

但如果失败:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: ClassB column: classB_id(should be mapped with insert="false" update="false")

版本:

休眠:5.2.12.FINAL JPA: hibernate-jpa-2.1-api

您不能使用@AttributeOverride 重命名外键列。你必须使用@AssosiactionOverride

@Entity
@Table(name = "TEST")
public class B {

    public long id;

    @AssociationOverride(name = "classB", joinColumns = @JoinColumn(name = "EMBEDDED1_ID"))
    @AttributeOverrides({
            @AttributeOverride(
                    name = "someEnum",
                    column = @Column(name = "EMBEDDED1_SOMEENUM")
            )
    })
    @Embedded
    public A embedded1;

    @AssociationOverride(name = "classB", joinColumns = @JoinColumn(name = "EMBEDDED2_ID"))
    @AttributeOverrides({
            @AttributeOverride(
                    name = "someEnum",
                    column = @Column(name = "EMBEDDED2_SOMEENUM")
            )
    })
    @Embedded
    public A embedded2;