我正在開發一個應用程序,使用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
什麼是使這項工作正確的方法?
謝謝
您是否找到解決方案? – mkurz
我在下面添加了一個答案。 – Joseph