[英]Components as composite identifiers in Hibernate
我正在關注Hibernate 文檔並嘗試實現第9.4. Components as composite identifiers
節中給出的示例9.4. Components as composite identifiers
9.4. Components as composite identifiers
但面臨如何實現它的問題。
這是我所做的:
我的實體類:
Order.java
public class Order {
private int id;
private Set<OrderLine> lines = new HashSet<OrderLine>();
// Setters & Getters
}
OrderLine.java
public class OrderLine {
private OrderLineId id;
private String name;
private Order order;
// Setters & Getters
}
OrderLineId.java
public class OrderLineId implements Serializable{
private int lineId;
private int orderId;
private int customerId;
// Setters & Getters
}
我的映射文件有問題:
<hibernate-mapping>
<class name="Order" table="TEST_Order">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<set name="lines" cascade="all">
<key column="orderId"/>
<one-to-many class="OrderLine"/>
</set>
</class>
<class name="OrderLine" table="TEST_OrderLine">
<composite-id name="id" class="OrderLineId">
<key-property name="lineId"/>
<key-property name="orderId"/>
<key-property name="customerId"/>
</composite-id>
<property name="name"/>
<many-to-one name="order" class="Order"
insert="false" update="false">
<column name="orderId"/>
<column name="customerId"/>
</many-to-one>
</class>
</hibernate-mapping>
當我嘗試創建一個解析此映射文件的會話工廠時,我收到一個異常消息:
Caused by: org.hibernate.MappingException: Foreign key (FK_89b4nqt5l2n6tfd1d5tq0ill0:TEST_OrderLine [orderId,customerId])) must have same number of columns as the referenced primary key (TEST_Order [id])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:110)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:93)
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1816)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1739)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
有人可以幫助我如何實現文檔中給出的示例。
OrderLine 需要引用 Order PK,它不是復合鍵。
這意味着多對一必須是:
<many-to-one name="order" class="Order"
insert="false" update="false">
<column name="orderId"/>
</many-to-one>
orderId 是 Order.id 的 FK。
那么一對多的一方將變成:
<set name="lines" cascade="all">
<key>
<column name="orderId"/>
</key>
<one-to-many class="OrderLine"/>
</set>
所以即使 OrderLine 有一個復合鍵,引用也是在 Order.id 之后進行的,它是一個簡單的鍵。
如果要將其他關聯映射到 OrderLine,例如 OrderLineProduct,則需要使用復合鍵來映射父級 (OrderLine) 和子級 (OrderLineProduct) 之間的關聯,以便 OrderLineProduct 具有復合外鍵回到訂單行。
在表 hbm 映射中,您應該具有相同的編號。 列,你用什么來制作復合材料。你需要在 TEST_Oder 中添加這 3 列。
要遵循的示例:
<many-to-one name="orderLine" class="OrderLine">
<column name="lineId"/>
<column name="orderId"/>
<column name="customerId"/>
</many-to-one>
引用相同的URL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.