AdSense

網頁

2018/7/26

Hibernate JPA Many To One複合主鍵新增時插入欄位順序錯誤

今天在使用Hibernate JPA的EntityManager.persist()新增主表和子表的資料時,出現插入欄位順序錯誤的問題,情形如下。

When INSERT data into the parent and child table by Hibernate JPA, the compound key fields of the child table was inserted with wrong order.

子表的主鍵為複合主鍵(Composite Key),分別由參照主表A及主表B的主鍵的外鍵所組成,主表B的主鍵也是複合主鍵。

The child table's primary key is composite key composed by foreign keys which reference to the primary keys of the parent table A and B, and B's primary key is also composite key.

+-----------+         +-------------+
|  ParentA  |         |    Child    |         +-----------+
+-----------+1       *+-------------+         |  ParentB  |
|PK|A1      +---------+FK|PK|A1     |*       1+-----------+
|  |        |         |FK|PK|B1     +---------+PK|B1      |
+--+--------+         |FK|PK|B2     |         |PK|B2      |
                      |FK|PK|B3     |         |PK|B3      |
                      +-------------+         +-----------+

但在新增主表A及所屬子表的資料時,在插入子表參照主表B的欄位資料時順序錯誤。

The problem is, when inserting data into ParentA and Child via Hibernate JPA, the foreign key fields data of the Child was inserted with wrong order.(eg. B1->B2, B2->B1)

原因為子表參考主表B物件的@ManyToOne@JoinColumns設定,當使用@JoinColumns來mapping多個@JoinColumn時,少設定了@JoinColumnreferencedColumnName屬性而發生。

也就是使用@JoinColumns時,必須設定@JoinColumnreferencedColumnName,其值為mapping的主表欄位名稱。請參考Hibernate JPA OneToMany/ManyToOne 主表為複合鍵(Compound Key)設定


參考:

沒有留言:

AdSense