2015-12-21 102 views
1

我正在開發一個應用程序,使用JPA 2.1和Hibernate 4.3作爲持久性提供程序。爲了提高可讀性和更好的維護性,我想明確地命名每一個可能的想法,而不是依賴於hibernate的命名策略。爲什麼@JoinTable上的JPA(Hibernate)外鍵定義不起作用?

我使用的是新引進的@ForignKey批註自定義forign鍵約束的名字,並能正常工作與@ManyToOne關係相關聯@JoinColumn

當嘗試使用@JoinTable自定義爲@ManyToMany關係生成的外鍵約束時,問題出現時,提供程序不使用我提供的名稱,並且還原爲其隨機生成的名稱。

例如:

@ManyToOne 
@JoinColumn(name = "store_id", referencedColumnName = "id", 
     foreignKey = @ForeignKey(name = "fk_collection_store_id")) 
Store store; 

正確生成以下DDL

alter table collection add constraint fk_collection_store_id foreign key (store_id) references store 

,但是當我嘗試與@ManyToMany協會使用它,它不按預期工作:

@ManyToMany 
@JoinTable(name="collection_product", 
     joinColumns = {@JoinColumn(name="collection_id", referencedColumnName = "id")}, 
     foreignKey = @ForeignKey(name = "fk_collection_product__collection_id"), 
     inverseJoinColumns = {@JoinColumn(name="product_id", referencedColumnName = "id")}, 
     inverseForeignKey = @ForeignKey(name = "fk_collection_product__product_id")) 
List<Product> products = new ArrayList<>(); 

生成的ddl不尊重我提供的名稱,並恢復爲自動生成的隨機名稱:

alter table collection_product add constraint FK_skd8u4feadi59mpp8os1q1ar3 foreign key (product_id) references product 

alter table collection_product add constraint FK_lbkv2n46sv06t6qfwabbk0wgw foreign key (collection_id) references collection 

那麼,這裏有什麼問題?

順便說一下,我試圖用外鍵的@JoinColumn本身的屬性(好像錯了,但我想也無妨),它並沒有幫助:

@ManyToMany 
@JoinTable(name="collection_product", 
     joinColumns={@JoinColumn(name="collection_id", referencedColumnName = "id", 
       foreignKey = @ForeignKey(name = "fk_collection_product__collection_id"))}, 
     inverseJoinColumns={@JoinColumn(name="product_id", referencedColumnName = "id", 
       foreignKey = @ForeignKey(name = "fk_collection_product__product_id"))}) 
List<Product> products = new ArrayList<>(); 

它不工作之一:

alter table collection_product add constraint FK_skd8u4feadi59mpp8os1q1ar3 foreign key (product_id) references product 

alter table collection_product add constraint FK_lbkv2n46sv06t6qfwabbk0wgw foreign key (collection_id) references collection 

什麼是使這項工作正確的方法?

謝謝

+0

您是否找到解決方案? – mkurz

+0

我在下面添加了一個答案。 – Joseph

回答

1

搜索Hibernate問題跟蹤器,我發現了幾個與此問題有關的錯誤報告。

它在5.x版本中部分修復。有些情況仍然沒有被新系統挑選出來,比如嵌入式持久類中的關係。 我打算立即提出一個錯誤

同時您可以升級到5.x版本,我使用5.1並且工作正常,而且幾乎沒有移植問題。

+0

它看起來像@ javax.persistence.ForeignKey註釋的屬性'foreignKeyDefinition'尚未在Hibernate中實現 - 請參閱https://hibernate.atlassian.net/browse/HHH-10643 – mkurz

相關問題