2015-12-21 70 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

相关问题