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

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

I have a Foo entity with:

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

Why doesn't Hibernate create a foreign key constraint on foo.bar -> bar.id?

+4
source share
2 answers

This is because MySQL does not support foreign key restrictions for tables created using ENGINE = MyISAM. You need to create (both!) Tables using ENGINE = InnoDB. You can do this by setting up my.cnf and adding a default value or using a special variable in the JDBC URL:

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

As suggested here by Hibernate: create Mysql InnoDB tables instead of MyISAM , you can also change the Hibernate dialogs to use

 org.hibernate.dialect.MySQL5InnoDBDialect 

which is less invasive.

Just wanted to add this as an alternative solution.

+5
source

Source: https://habr.com/ru/post/1389180/


All Articles