簡體   English   中英

通過組合Java中另一個表的一列來創建表

[英]Create a table by combining one column from another table in Java

經過一些研究,我找不到相關的東西。

我用一個表如下:

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

和CombinedProductsPK:

@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`)
)

我在這里走到了盡頭,所以也許我走錯了路。 每個推薦被接受! 提前致謝...

我沒聽懂你的意思。 但也許你需要嘗試@JoinTable呢?

在此輸入鏈接描述

我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM