springhibernatejpaspring-annotationsjparepository

How to implements entity with 2 entity as primary key with jpa annotation and repository


i want to implement a many to many association with quantity information in it . like this :

@Entity
@Table(name = "reserves")
@Getter @Setter @NoArgsConstructor
public class Reserve {
    @Id
    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "groupe_id")
    private GroupeSanguin bloodGroup;
    @Id
    @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private Banque banque;
    private int quantity;
}

the GroupSanguin and the Banque are two class stored in the database two . here is the code for the two if you need :

@Entity
@Table(name = "groupe_sanguins")
public class GroupeSanguin {
    @Id
    private String groupe;
    @OneToMany(mappedBy = "groupeSanguin")
    private List<Donneur> donneurs;
}
@Entity @Getter @Setter @NoArgsConstructor
public class Banque {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true,nullable = false)
    private String nom;
    private String adresse;
    @Column(unique = true)
    private String telephone;
    private String localisation;
}

so my i want to know how to annotate the JpaRepository to take the two as primary key like this and is my annotation good for it to work ?

public interface ReserveRepository extends JpaRepository<
Reserve,
//what to put here ?
>

Solution

  • i've found this solutions too.

    @Entity
    @Table(name = "reserves")
    @Getter @Setter @NoArgsConstructor
    @IdClass(ReserveId.class) //this annotation will tell that id that the 
    // the id will be represented by a class
    public class Reserve {
        @Id
        @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
        @JoinColumn(name = "groupe_id")
        private GroupeSanguin groupeSanguin;
        @Id
        @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
        @JoinColumn(name = "banque_id")
        private Banque banque;
        private int quantity;
    }
    

    and the id class should implements Serializable like this :

    @Getter @Setter
    public class ReserveId implements Serializable {
        private Banque banque;
        private GroupeSanguin groupeSanguin;
    }
    

    and finally the repository will be like that :

    @Repository
    public interface ReserveRepo extends JpaRepository<Reserve, ReserveId>{}