简体   繁体   中英

How do you join an object with a composite id on another object with a composite id but not the same composite id? (JPA annotations)

How would you map a list of bar objects onto the Foo object, using ONLY the FOO_ID?

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

I've tried: @JoinColumn (as above) and @JoinTable on another table that contains the FOO_ID as the primary key. Neither works.

Try as described here: http://stackoverflow.com/questions/5305687/join-entity-with-composite-key

Foo doesn't do any special mapping:

class Foo {
    @EmbeddedId
    private FooPK primaryKey;

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

So map it on the other side:

class Bar {
    @EmbeddedId
    private BarPK primaryKey;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM