java - 如何在 Hibernate 实体注释上使用两个外键作为主键

标签 java mysql hibernate

我想使用 Hibernate 实体注释从 2 个外键创建一个主键: look at the picture please **

  • 如何将这两个外键“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;
}

它有效,看图片: enter image description here

关于java - 如何在 Hibernate 实体注释上使用两个外键作为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599321/

相关文章:

java - 如何实现xxx.domainname.com URL模式?

java - 没有 SockJS/StompJS 的 Spring STOMP 服务器

Java Formatter 类,有没有一种简单的方法可以用空格自动填充列?

mysql - CodeIgniter 中的多个连接非常慢 - 如何加快速度

mysql - 这个MySQL存储过程如果使用prepared statements是否还有SQL注入(inject)的风险?

java - Spring Hibernate SessionUtils connection.close

java - 向 Spring 和 Hibernate 5 注册事件监听器

JavaParser 读取 src 目录

php - 为什么在使用 MySQLi 在 PHP 中准备句子时显示错误

java - hibernate ——连接被拒绝