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 ?
As suggested here Hibernate: Create Mysql InnoDB tables instead of MyISAM you can also change Hibernate dialect to use
org.hibernate.dialect.MySQL5InnoDBDialect
which is less invasive.
Just wanted to add this as an alternative solution.
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
With SpringBoot you can set application.properties
to:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
and it should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With