hbm2ddl-如何避免Hibernate创建外键约束?

hbm2ddl-如何避免Hibernate创建外键约束?

问题描述:

亲爱的我正在将Hibernate与hbm2ddl结合使用.我不喜欢为一种关系创建外键约束.不幸的是,到目前为止我还没有实现.我尝试了Hibernate和JPA批注,但是没有运气. 有什么提示吗?

Dear all I am using Hibernate with hbm2ddl. I don't like that for one relationship foreign key constraints get created. Unfortunately I could not achieve it so far. I tried it with Hibernate and JPA annotations, had no luck. Any hints?

我正在使用Hibernate 4.3.1和mysql 5.6

I am using Hibernate 4.3.1 and mysql 5.6

@Entity
class Artikel {
   ...
   @OneToMany(fetch=FetchType.LAZY, mappedBy="artikel")
   @NotFound(action=NotFoundAction.IGNORE)
   private List<Bild> images;
}

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
@Entity
class Bild {
  @ManyToOne(fetch=FetchType.LAZY)
  @org.hibernate.annotations.ForeignKey(name = "none") 
  @JoinColumn(name="idKey",  insertable=false, updatable=false, 
    foreignKey = @ForeignKey(name="none",value = ConstraintMode.NO_CONSTRAINT)) 
  private Artikel artikel;
}

它将始终创建外键:FK_k93uxcqtc87jifh2j3rliumuj用于表"bild"的列"idKey": 导入期间出错:无法添加或更新子行:外键约束失败(skateshop.bild,CONSTRAINT FK_k93uxcqtc87jifh2j3rliumuj外国密钥(idKey)参考artikel(id))" /p>

It always creates the foreign key: FK_k93uxcqtc87jifh2j3rliumuj for table "bild" on column "idKey": Error during import: "Cannot add or update a child row: a foreign key constraint fails (skateshop.bild, CONSTRAINT FK_k93uxcqtc87jifh2j3rliumuj FOREIGN KEY (idKey) REFERENCES artikel (id))"

您使用的是正确的注释:

You are using the correct annotation:

@ForeignKey(value = ConstraintMode.NO_CONSTRAINT)

这似乎是休眠4.x中的错误,现已在5.x中修复.如果您可以升级到Hibernate 5.x,则可以解决此问题.

It looks like a bug in hibernate 4.x that is now fixed in 5.x. If you could upgrade to Hibernate 5.x, that would solve the issue.

另请参见没有外键的JPA关联