11

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 ?

George Armhold
  • 30,824
  • 50
  • 153
  • 232

3 Answers3

18

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.

Community
  • 1
  • 1
konqi
  • 5,137
  • 3
  • 34
  • 52
14

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
George Armhold
  • 30,824
  • 50
  • 153
  • 232
10

With SpringBoot you can set application.properties to:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect   

and it should work fine.

Milo
  • 3,365
  • 9
  • 30
  • 44
Thiago Matar
  • 111
  • 1
  • 3