Search code examples
jpaorm

JPA ManyToOne with composite key


I have this model mapping for a Brand entity:

@Entity
public class Brand implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private BrandPk id;

//...
}

The composite key is:

@Embeddable
public class BrandPk implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id1;

    private int id2;
//...
}

Now I want to join a Product entity (one brand, many products):

I will have:

@Entity
public class Product implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

@ManyToOne
// ???
private Brand brand;

//...
}

What will I need to correctly join my tables-entities?

table_brands has a PK composing two fields: id1 and id2 table_products has a PK with an id, and a field id_brand refering just to id1.

id2 is not used anymore and not important at all!

This mapping is for a legacy DB that unfortunately I cannot change, so I need to join "ignoring" id2. How can I?


Solution

  • If you add another column say id_brand2 referring to id2, you can try this:

    @ManyToOne
    @JoinColumns({
         @JoinColumn(name="id_brand", referencedColumnName="id1"),
         @JoinColumn(name="id_brand2", referencedColumnName="id2")
    })
    private Brand brand;