1

因此经过一番研究后,我找不到相关的东西。通过组合Java中另一个表的一列来创建表格

我用如下一个表:

@Table(name="product") 
public class Product { 
    @Id 
    @GeneratedValue 
    private long productId; 

    // other irrelevant columns and code goes here 
} 

现在,我想创建另一个表,它是这样:

table columns and what rows I want to show

要作出这样的,我想是这样的以下其他示例或样本:

@Table(name="combined_products") 
public class CombinedProducts { 

    @EmbeddedId 
    protected CombinedProductsPK bridgeId; 

    @ManyToOne 
    @JoinColumns({ 
     @JoinColumn(name = "product_1", referencedColumnName = "product_id"), 
     @JoinColumn(name = "product_2", referencedColumnName = "product_id") 
    }) 

    @Column(name = "notes") 
    private String notes; 

    public ProductMatrix() { 
     bridgeId = new CombinedProductsPK(); 
    } 

    // irrelevant code again 
} 

和C ombinedProductsPK:

@Embeddable 
public class CombinedProductsPK implements Serializable { 

    public Long product_1; 
    public Long product_2; 

    public CombinedProductsPK() {} 

    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) { 
     return true; 
     } 
     CombinedProductsPK b = (CombinedProductsPK)obj; 
     if (b == null) { 
     return false; 
     } 
     return b.product_1.equals(product_1) && b.product_2.equals(product_2); 
    } 

    @Override 
    public int hashCode() { 
     return (int)(product_1 + product_2); 
    } 
} 

和所有似乎工作完美。

但是,我的问题是,当我看看数据库,并具体到combined_products表,有没有 FOREIGN_KEY约束。有什么方法可以在Java中描述这个约束,或者我必须手动在Java部分中处理这个问题?

这是我的表看起来像在MySQLWorkbench

CREATE TABLE `combined_products` (
    `product_1` bigint(20) NOT NULL, 
    `product_2` bigint(20) NOT NULL, 
    `notes` varchar(255) DEFAULT NULL, 
    PRIMARY KEY (`product_1`,`product_2`) 
) 

我这里钻牛角尖我,也许我跟随路线错误。每个建议都被接受!在此先感谢...

回答

相关问题