[英]How to getList using JPA when the first entity is the following entity after the entity with specified primary key
[英]How to implements entity with 2 entity as primary key with jpa annotation and repository
我想與其中的數量信息實現多對多關聯。 像這樣:
@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;
}
GroupSanguin 和 Banque 是兩個 class 存儲在數據庫中的兩個。 如果需要,這是兩者的代碼:
@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;
}
所以我想知道如何注釋 JpaRepository 以將兩者作為主鍵,我的注釋是否適合它工作?
public interface ReserveRepository extends JpaRepository<
Reserve,
//what to put here ?
>
實際上,這不是 JPA 問題,而是關系數據庫概念。 如果 Reserve 有自己的數據並與其他實體鏈接它有自己的 Id您可以添加唯一性約束
@Entity
@Table(name = "reserves", uniqueConstraints={
@UniqueConstraint(columnNames = {"banque_id", "groupe_id"})
@Getter @Setter @NoArgsConstructor
public class Reserve {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "groupe_id")
private GroupeSanguin bloodGroup;
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "banque_id")
private Banque banque;
private int quantity;
}
我也找到了這個解決方案。
@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;
}
並且 id class 應該像這樣實現 Serializable :
@Getter @Setter
public class ReserveId implements Serializable {
private Banque banque;
private GroupeSanguin groupeSanguin;
}
最后存儲庫將是這樣的:
@Repository
public interface ReserveRepo extends JpaRepository<Reserve, ReserveId>{}
查看您的 Reserve class 沒有提到復合主鍵。 首先你需要修復model,你可以參考這里的解決方案How to create and processing composite primary key in JPA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.