问题
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?
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;
}
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
))"
回答1:
You are using the correct annotation:
@ForeignKey(value = ConstraintMode.NO_CONSTRAINT)
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.
See also JPA association without foreign key
来源:https://stackoverflow.com/questions/32154592/hbm2ddl-how-to-avoid-that-hibernate-is-creating-foreign-key-constraints