简体   繁体   中英

JPA annotation for parent composite key to be part of child composite primary key

I am trying to map a race day that has multiple races, and can't figure out the annotations.

What I want to end up with is something like (this is a simplified example):

TABLE: race_day
    date (PK)
    venue (PK)
    description

TABLE: race
    date (PK but also FK on race_day table)
    venue (PK but also FK on race_day table)
    race_number (PK)
    description

So far I've come up with the following POJO + annotations:

public class RaceDayPK implements Serializable {

    @Column(name="race_date")
    private String raceDate;
    @Column(name="venue")
    private String venue;
...
}

public class RaceDay {

    @EmbeddedId
    private RaceDayPK raceDayPk;

    @OneToMany(mappedBy = "raceDay", orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    private final List<Race> races = new ArrayList<>();

...
}

public class Race {

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "race_date", referencedColumnName = "race_date"),
        @JoinColumn(name = "venue", referencedColumnName = "venue")
    })
    private RaceDay raceDay;

    private int raceNumber;
    private String raceTitle;
...
}

How do I make an EmbeddedId for Race (I'm guessing that's what I need) with both the raceDay join column AND raceNumber in it? Any help appreciated. I have seen dozens of JoinColumn examples and EmbeddedId examples here on StackOverflow but none that seem to combine the two in the way that I need.

After some hacking around, I think I got it working like this. Note the nested "racePk.raceMeeting" in the mappedBy parameter for the OneToMany annotation:

public class RaceDayPK implements Serializable {

    @Column(name="race_date")
    private String raceDate;
    @Column(name="venue")
    private String venue;
...
}


public class RaceDay {

    @EmbeddedId
    private RaceDayPK raceDayPk;

    @OneToMany(mappedBy = "racePk.raceDay", orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    private final List<Race> races = new ArrayList<>();

...
}


public class RacePk implements Serializable {

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "race_date", referencedColumnName = "race_date"),
        @JoinColumn(name = "venue", referencedColumnName = "venue")
    })
    private RaceDay raceDay;
    @Column(name = "race_number")
    private int raceNumber;
...
}


public class Race {

    @EmbeddedId
    private final RacePk racePk = new RacePk();
    private String raceTitle;
...
}

No idea yet whether this will fall over at some point but the MySQL tables appear to have been auto-generated correctly.

TABLE: race_day
        id(PK)
        date (PK)
        venue (PK)
        description

TABLE: race
        id(PK but also FK on race_day table)
        date (PK but also FK on race_day table)
        venue (PK but also FK on race_day table)
        race_number (PK)
        description

For the above given tables, I was able to generate the sequence and get the data persisted in the tables following the constraints using the below code.

    public class RaceDayPK implements Serializable {

        private Long id;
        private String raceDate;
        private String venue;
    ...
    }

    @Entity
    @IdClass(RaceDayPK.class)
    public class RaceDay {

        @Id
        @Column(name="id")
        @GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "R_SEQ")
        @SequenceGenerator(sequenceName = "RD_SEQ", allocationSize = 1, name = "R_SEQ")
        private Long id;

        @Id
        @Column(name="race_date")
        private String raceDate;

        @Id
        @Column(name="venue")
        private String venue;

        @OneToMany(mappedBy = "raceDay", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
        private Set<Race> races;

    ...
    }

    public class RacePK implements Serializable {


        private RaceDay raceDay;
        private int raceNumber;
    ...
    }

    @Entity
    @IdClass(RacePK.class)
    public class Race {

        @Id
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumns({
            @JoinColumn(name = "race_date", referencedColumnName = "race_date"),
            @JoinColumn(name = "venue", referencedColumnName = "venue"),
            @JoinColumn(name = "id", referencedColumnName = "id")
        })
        @JsonIgnore
        private RaceDay raceDay;

        @Id
        private int raceNumber;

        private String raceTitle;
    ...
    }

the dao code needs to be changed a bit as to below.

public RaceDay saveRaceDay(RaceDay raceDay){
 if(raceDay.getRaces()!=null){
            raceDay.getRaces().forEach(race ->{
                race.setRaceDay(raceDay);
            });
        }
        }

Not sure if it works but try this approach:

public class RacePK implements Serializable {

    private RaceDayPK raceDay;    
    private String raceNumber;
...
}

@Entity
@IdClass(RacePK.class)
public class Race {

    @Id 
    @ManyToOne...
    private RaceDay raceDay;

    @Id
    private int raceNumber;
    private String raceTitle;
...
}

Note that PK field names should be exactly the same as @id-annotaed field names. Google for Derived identifiers to learn more.

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