【问题标题】:How to use two foreign keys as primary key on Hibernate entity annotation如何在 Hibernate 实体注释中使用两个外键作为主键
【发布时间】:2014-12-23 07:49:05
【问题描述】:

我想使用 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;
    }
}

“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;
    }
}

除此之外我没有任何异常或错误!!

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    这是解决方案:

    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;
    }
    

    它有效,请看图片:

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多