我想使用 Hibernate 实体注释从 2 个外键创建一个主键: **
- 如何将这两个外键“comID”和“reference”设置为 带 Hibernate 注释的 LigneCommande 表的主键! 谢谢:)
我尝试了这段代码,但它不起作用:
“产品”类:
public class Produit implements Serializable{
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "LigneCommande", catalog = "mkyongdb", joinColumns = {
@JoinColumn(name = "reference", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "commande_id",
nullable = false, updatable = false) })
private List<Commande> commande;
public List<Commande> getCommande() {
return commande;
}
public void setCommande(List<Commande> commande) {
this.commande = commande;
}
}
“指挥官”类:
@Entity
public class Commande implements Serializable{
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "commande")
private List<Produit> produit;
public List<Produit> getProduit() {
return produit;
}
public void setProduit(List<Produit> produit) {
this.produit = produit;
}
}
最重要的是,我没有任何异常或错误!!
最佳答案
这是解决方案:
public class LigneCommande implements Serializable {
@EmbeddedId
protected LigneCommandePK ligneCommandePK;
@Column(name = "quantite")
private int quantite;
@Column(name = "status")
private String status;
@JoinColumn(name = "produit_id", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Produit produit;
@JoinColumn(name = "commande_id", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Commande commande;
}
这是“产品”类:
@Entity
@Table(name = "produit")
public class Produit implements Serializable {@OneToMany(cascade = CascadeType.ALL, mappedBy = "produit")
private Collection<LigneCommande> ligneCommandeCollection;
}
这是关联类:
@Embeddable
public class LigneCommandePK implements Serializable {
@Basic(optional = false)
@Column(name = "commande_id")
private int commandeId;
@Basic(optional = false)
@Column(name = "produit_id")
private int produitId;
}
它有效,看图片:
关于java - 如何在 Hibernate 实体注释上使用两个外键作为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599321/