gpt4 book ai didi

java - Jpa子类映射

转载 作者:行者123 更新时间:2023-12-01 16:04:17 26 4
gpt4 key购买 nike

我正在制作一个类似 POS 的系统。我想知道如何使用 JPA 映射子类(这是针对我的 DAO 的)。 Product 类包含产品详细信息,OrderProduct 类包含有关 Product 的信息以及有关订单的详细信息。

@Entity
@Table(name="products")
public class Product implements Serializable{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO
public int getId(){ return id;}

/**
Other get/set methods
*/
}

@Entity
@Table(name="order_products")
public class OrderProduct extends Product{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId(){ return id;}

/**
Other get/set methods
*/
}

我收到关于重复 @Id 的投诉。但是 OrderProduct 类确实需要另一个 id 而不是产品 id。我应该如何映射它?

数据库是这样的

Table products
id int
name varchar(32)

Table order_product
id int
quantity int
productid int fk referencing product table

@IdClass@AttributeOverride 有帮助吗?

最佳答案

我认为使用 JPA 和 Hibernate 都无法实现您想要实现的目标。当使用连接子类策略时,子类的 PK 是基类的 PK,用于执行表之间的连接。来自 JPA 规范:

2.1.10.3 Joined Subclass Strategy

In the joined subclass strategy, the root of the class hierarchy is represented by a single table. Each subclass is represented by a separate table that contains those fields that are specific to the subclass (not inherited from its superclass), as well as the column(s) that represent its primary key. The primary key column(s) of the subclass table serves as a foreign key to the primary key of the superclass table.

您可以使用@PrimaryKeyJoinColumn来更改子类中的列名称:

@Entity
@PrimaryKeyJoinColumn(name="PRODUCT_ID", referencedColumnName = "ID")
public class OrderProductTop extends ProductTop {
...
}

但是 PRODUCT_ID 仍然是 PK。

说实话,我不明白你的物理模型。对我来说,您当前所代表的是一对多关系,这是不正确的(应该是一对一)。

关于java - Jpa子类映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com