我正在开发一个应用程序,使用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