【问题标题】:Create a table by combining one column from another table in Java通过在 Java 中组合另一个表中的一列来创建一个表
【发布时间】: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


    【解决方案1】:

    我没明白你的意思。但也许您需要为此尝试@JoinTable?

    enter link description here

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2022-01-23
      • 2021-05-13
      • 2012-08-30
      • 2019-12-25
      • 1970-01-01
      相关资源
      最近更新 更多