JPA joins a table with multiple objects

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 that OneToMany relationships are based on a type column (enumeration)? For example, if part of it or any other entity automatically receives the related entity.

Thanks in advance.

+3
source share
1 answer

In your PK object, you do not need to store identifiers as long (in fact, this is true every time you need a reference to the object). When compared with the actual database schema, the JPA replaces all references to other objects with object identifiers.

, ( , "" ):

@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 , : "long npc_id", "Npc npc"; "long good_id", "".

: @Column @ManyToOne. @JoinColumn, , .

, "". "nullable" .

: ah, Npc NpcTradeGoodPK, , Npc , . .

+3

Source: https://habr.com/ru/post/1715033/


All Articles