有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带子类的javajpa

我对JPA很陌生。我最近学会了如何处理类与类之间的关系,但不知道当涉及到子类以及父母与孩子之间的关系时该怎么做

这是我的问题,我想我最终会得到什么

我有一个抽象类,Product。该产品将包含所有产品共有的字段(它将具有产品id、名称、说明和价格)。 从产品延伸,我有一本书。这本书还有一个属性是author。 衬衫也是该产品的延伸。衬衫还有一个特定属性,即尺寸

因此,我希望数据库如下所示:

========

产品 产品标识(pk), 名称 描述 价格

========

=========

书 产品标识(pk fk), 作者

=========

=========

衬衫 产品标识(pk fk), 大小

==========

如您所见,book and shirt中的主键是product_id,这也是product的外键。书籍和产品之间存在一对一的关系。衬衫和产品之间也是一对一的关系

我找到了一些教程,但它们没有很好地解释,对于这个特定的问题也没有太大的帮助

提前谢谢,谢谢你的帮助

编辑:

在尝试了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;
}

}

衬衫上的代码:

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

}

书中的代码是:

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

}

我还尝试将book和shirt中的表名更改为“EPOS_book”和“EPOS_shirt”,但仍然出现错误。我得到:

SQLGrammarException:无法执行JDBC批处理更新

以及:

BatchUpdateException:ORA-01747:无效用户。桌子列,表。列,或列规范

这是它尝试运行的查询:

休眠: 选择 休眠顺序。下特瓦尔 从…起 二重的 冬眠: 选择 休眠顺序。下特瓦尔 从…起 二重的 冬眠: 插入 进入 EPOS_产品 (名称、价格、作者、帖子类型、产品id) 价值观 (?,?,?,“书”,?)


共 (1) 个答案

  1. # 1 楼答案

    在JPA中,使用@Inheritance注释和存储实体的策略对继承关系进行建模。考虑到您当前的数据模型,我倾向于每类表策略

    基本上,你会得到:

    • 每个派生类的表和实体。抽象类不接收自己的表
    • 定义了策略的抽象类上的@Inheritance注释@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

    关于此策略,您可能有一个误解,即Product类将被持久化到数据库中。相反,product类中的字段应该在BookShirt表中重复

    有关每个类的表的教程,请参见我的博客:http://blog-tothought.rhcloud.com/post/22