我正面临父子类型关系的问题。
Hibernate文档说要在子类中添加“多对一”关系,以从父级获取外键的值。但是,要使此关系正常工作,我必须在子类中添加Invoice属性,从而在子类中引入父级的循环包含,并破坏我的序列化器。有人可以指出我在哪里做错吗?
这是我的代码:
发票.java
public class Invoice implements Serializable {
private Long id;
private Date invDate;
private String customer;
private Set<InvoiceItem> items;
... getters/setters ...
}
InvoiceItem.java
public class InvoiceItem implements Serializable {
private Long itemId;
private long productId;
private int quantity;
private double price;
private Invoice invoice; //???????
... getters/setters ...
}
Invoice.hbm.xml
<class name="Invoice" table="Invoices">
<id name="id" column="ID" type="long">
<generator class="native" />
</id>
<property name="invDate" type="timestamp" />
<property name="customer" type="string" />
<set name="items" inverse="true" cascade="all-delete-orphan">
<key column="invoiceId" />
<one-to-many class="InvoiceItem" />
</set>
</class>
InvoiceItem.hbm.xml
<class name="InvoiceItem" table="InvoiceItems">
<id name="itemId" type="long" column="id">
<generator class="native" />
</id>
<property name="productId" type="long" />
<property name="quantity" type="int" />
<property name="price" type="double" />
<many-to-one name="invoiceId" class="Invoice" not-null="true"/> <!--????????-->
</class>
最佳答案
如果删除inverse =“ true”属性,则不必在InvoiceItem中具有对Invoice的引用。
然后,Hibernate将创建一个单独的映射表,而不是在InvoiceItem表中使用外键。
删除InvoiceItem集合上的inverse
属性,还从InvoiceItem中删除Invoice属性,并在映射中删除相应的many-to-one
,您应该获得所需的内容。
或者,您可以将InvoiceItem中的Invoice引用标记为瞬态,并在反序列化期间处理填充值:迭代Invoice中的Set of Items,并将每个项目的invoice
属性设置为拥有的发票。
关于java - hibernate 的 parent /子女关系问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3255073/