使用MySQL,为什么Hibernate / JPA不会为我创建外键约束? [英] Using MySQL, why doesn't Hibernate/JPA create foreign key constraints for me?

查看:312
本文介绍了使用MySQL,为什么Hibernate / JPA不会为我创建外键约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个实体Foo:

  @ManyToOne(可选= false)
@JoinColumn(name =barId)
私人酒吧;

为什么Hibernate不在foo.bar上创建外键约束 - > bar.id?

解决方案

这是因为MySQL不支持使用ENGINE = MyISAM创建的表的外键约束。您需要使用ENGINE = InnoDB创建(两个!)表。您可以通过调整 my.cnf 并添加一个默认值,或者在您的JDBC URL中使用一个特殊变量来实现:

  jdbc:mysql:// localhost / dbname?characterEncoding = utf8& sessionVariables = storage_engine = InnoDB 


Documenting this here because I just wasted an hour trying to figure this out.

I have an entity Foo with:

@ManyToOne(optional = false)
@JoinColumn(name = "barId")
private Bar bar;

Why does Hibernate not create a foreign key constraint on foo.bar -> bar.id ?

解决方案

It's because MySQL does not support foreign key constraints on tables created with ENGINE=MyISAM. You need to create (both!) tables with ENGINE=InnoDB. You can do so by tweaking my.cnf, and adding a default, or by using a special variable in your JDBC URL:

jdbc:mysql://localhost/dbname?characterEncoding=utf8&sessionVariables=storage_engine=InnoDB

这篇关于使用MySQL,为什么Hibernate / JPA不会为我创建外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆