tags:

views:

1189

answers:

1

Hi, I have an Entity that looks like this:

public class NpcTradeGood implements Serializable, Negotiabble {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected NpcTradeGoodPK npcTradeGoodPK;
    @JoinColumn(name = "npc_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Npc npc;
}

@Embeddable
public class NpcTradeGoodPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "npc_id", nullable = false)
    private long npcId;
    @Basic(optional = false)
    @Column(name = "good_id", nullable = false)
    private long goodId;
    @Basic(optional = false)
    @Column(name = "type", nullable = false)
    @Enumerated(EnumType.STRING)
    private ItemType type;
}

Is there a way to tell JPA which OneToMany relationship it is based on the type column (enumeration)? Like if its a part or any other entity it automatically gets the related entity.

Thanks in advance.

+1  A: 

In your PK object, you don't need to store the ids as longs (actually, this is true every time you need a reference to an entity). When mapping to the actual DB schema, JPA replaces all the references to other entities by thoes entities' ids.

So, if you use this (notice that I replaced your 'long' ids with actual references to the entities):

@Embeddable
public class NpcTradeGoodPK implements Serializable {
    @ManyToOne
    @JoinColumn(name = "npc_id", nullable = false)
    private Npc npc;
    @ManyToOne
    @JoinColumn(name = "good_id", nullable = false)
    private Good good;
    @Column(name = "type", nullable = false)
    @Enumerated(EnumType.STRING)
    private ItemType type;
}

... JPA will map this to the DB, using: "long npc_id" where we refer to "Npc npc"; and "long good_id" where we refer to "Good good".

One important thing: you cannot use @Column with @ManyToOne. You may use @JoinColumn instead which will allow you to do the same things you do now.

Also, you don't need to specify all those 'optionals'. 'nullable' should take care of that.

Edited: ah, the Npc in NpcTradeGoodPK will probably collide with the Npc in the entity that embeds it. Consider renaming one of them.

ptdev