[英]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.