簡體   English   中英

帶有子類的JPA

[英]JPA with subclasses

我對JPA很陌生。 我最近學習了如何在類之間建立關系,但是不確定在擁有子類以及父母與孩子之間的關系時該怎么做。

這是我的問題,我要結束的是...

我有一個抽象類Product。 產品將包含所有產品共有的字段(它將具有product_id,名稱,描述和價格)。 從產品擴展,我有書。 本書還有一個屬性是作者。 從產品擴展的還有襯衫。 襯衫還有一個特定的屬性,即尺寸。

所以我希望數據庫看起來像這樣:

========

PRODUCT product_id(pk),名稱,描述,價格

========

=========

圖書product_id(pk fk),作者

=========

=========

襯衫product_id(pk fk),尺寸

==========

如您所見,book和Shirt的主鍵將是product_id,這也是產品的外鍵。 書籍和產品之間存在一對一的關系。 襯衫與產品之間也是一對一的關系。

我已經找到了一些教程,但是他們沒有很好地解釋它,並且對於這個特定問題不是很有用。

在此先感謝,感謝您的幫助。

編輯:

在嘗試了我在Kevin Bowersox的github上發現的內容之后,仍然真的堅持了這一點。 這是我的產品代碼:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@Table(name = "EPOS_Product")
@DiscriminatorColumn(name="POST_TYPE", discriminatorType=DiscriminatorType.STRING)
public abstract class Product {

@Id @GeneratedValue
@Column(name = "product_id")
protected int id;

@Column(name = "name")
protected String name;

@Column(name = "price")
protected double price;


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

}

Shirt中的代碼:

@Entity
@Table(name="EPOS_Product")
@DiscriminatorValue(value="Shirt")
public class Shirt extends Product{

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

public Shirt(){}

public Shirt(String name, double price, String size){
    this.name = name;
    this.price = price;
    this.size = size;       
}

public String getSize() {
    return size;
}

public void setSize(String size) {
    this.size = size;
}

}

以及Book中的代碼:

@Entity
@Table(name="EPOS_Product")
@DiscriminatorValue(value="Book")
public class Book extends Product{

private String author;

public Book(){}

public Book(String name, double price, String author){
    this.name = name;
    this.price = price;
    this.author = author;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}       

}

我還嘗試將書和襯衫中的表名稱更改為“ EPOS_Book”和“ EPOS_Shirt”,但仍然出現錯誤。 我得到:

SQLGrammarException:無法執行JDBC批更新。

和:

BatchUpdateException:ORA-01747:無效的user.table.column,table.column或列規范。

這是它嘗試運行的查詢:

休眠:從雙休眠中選擇hibernate_sequence.nextval休眠:從雙休眠中選擇hibernate_sequence.nextval:插入EPOS_Product(名稱,價格,作者,POST_TYPE,product_id)值(?,?,?,'Book'、?)

在JPA中,使用@Inheritance批注和用於存儲實體的策略對繼承關系進行建模。 給定您當前的數據模型,我將傾向於按班級使用表格。

基本上,您將獲得:

  • 每個派生類的表和實體。 抽象類沒有收到自己的表。
  • 抽象類上的@Inheritance批注,其中定義了策略。 @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

您可能對這種策略有一個誤解,就是將Product類保留在數據庫中。 而是應該在BookShirt表中重復產品類中的字段。

有關每個班級表的教程,請參見我的博客: http : //blog-tothought.rhcloud.com/post/22

暫無
暫無

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

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