【发布时间】:2017-09-18 09:38:57
【问题描述】:
所以经过一些研究,我找不到相关的东西。
我用一张表如下:
@Table(name="product")
public class Product {
@Id
@GeneratedValue
private long productId;
// other irrelevant columns and code goes here
}
现在,我想创建另一个表格,如下所示:
为此,我按照其他示例或示例尝试了类似的方法:
@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
}
和组合产品PK:
@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);
}
}
一切似乎都很完美。
但是,我的问题是,当我查看数据库并特定于 combine_products 表时,存在 no 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`)
)
我在这里陷入了死胡同,所以也许我走错了路。每个建议都被接受!提前谢谢...
【问题讨论】:
标签: java hibernate annotations hibernate-mapping foreign-key-relationship