Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MySQL, why doesn't Hibernate/JPA create foreign key constraints for me?

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 ?

like image 307
George Armhold Avatar asked Jan 04 '12 00:01

George Armhold


3 Answers

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.

like image 111
konqi Avatar answered Nov 14 '22 11:11

konqi


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
like image 14
George Armhold Avatar answered Nov 14 '22 10:11

George Armhold


With SpringBoot you can set application.properties to:

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

and it should work fine.

like image 10
Thiago Matar Avatar answered Nov 14 '22 09:11

Thiago Matar