如何在具有复合id但不具有相同复合ID的另一个对象上加入具有复合id的对象? (JPA注释)

时间:2013-03-22 16:20:21

标签: java hibernate jpa annotations jpa-2.0

如何仅使用FOO_ID将条形图对象列表映射到Foo对象?

@Entity
@Table(name="FOO")
class Foo {
    @EmbeddedId
    private FooPK primaryKey;

    @OneToMany
    @JoinColumn(name="FOO_ID", referencedColumnName="FOO_ID") //does not work
    private List<Bar> bars;
}

@Embeddable
class FooPK {
    @Column(name="FOO_ID")
    private String id;

    @Column(name="FOO_SUB_ID")
    private String subId;
}

@Entity
@Table(name="BAR")
class Bar {
    @EmbeddedId
    private BarPK primaryKey;

    //other attributes and methods
}

@Embeddable
class BarPK {
    @Column(name="FOO_ID")
    private String id;

    @Column(name="BAR_ID")
    private String barId;

    @Column(name="BAR_SUB_ID")
    private String barSubId;
}

我尝试过:@JoinColumn(如上所述)和@JoinTable在另一个包含FOO_ID作为主键的表上。两者都不起作用。

1 个答案:

答案 0 :(得分:0)

按照此处的说明进行尝试: http://stackoverflow.com/questions/5305687/join-entity-with-composite-key

Foo没有做任何特殊的映射:

class Foo {
    @EmbeddedId
    private FooPK primaryKey;

    @OneToMany(mappedBy="foo")
    private List<Bar> bars;
}

所以将它映射到另一边:

class Bar {
    @EmbeddedId
    private BarPK primaryKey;

    @ManyToOne
    @MapsId("id")
    private Foo foo;
}