To implement an parent object in one-to-many relation with a child object that has a composite primary key (i.e. multiple columns as primary key) is not quite straightforward.

We need to use a mix of JPA annotations along with creating some embeddable classes.

Suppose we have the following representation in our database:

+=======+          +=============+          +=======+
|cat    |          |cat_toy_usage|          |toy    |
|-------|1        N|-------------|N        1|-------|
|cat_id*|----------|cat_id*      |----------|toy_id*|
|name   |          |toy_id*      |          |name   |
+=======+          |usage_status |          +=======+

We have:

  • cats
  • toys for cats
    • a toy can be shared between cats
  • an usage status (either USED or UNUSED)

Using JPA, we will have the following:

public class Cat implements Serializable {
    private Long catId;

    private String name;

    @OneToMany(mappedBy="", fetched = FechType.LAZY, cascade = CascadeType.ALL)
    private Set<CatToyUsage> toyUsages;

    // Getters + setters

public class CatToyUsage implements Serializable {
    static class Pk implements Serializable {
        @JoinColumn(name = "cat_id")
        private Cat cat;

        @Column(nullable = false, updatable = false)
        private Long toyId;

        // Getters + setters + equals + hashCode

    private Pk id;

    private UsageStatus usageStatus;

    // Getters + setters