Health-Genie

[MySQL 1822 에러] Failed to add the foreign key constraint

j9972 2023. 6. 2. 21:42
728x90

Failed to add the foreign key constraint

이 에러는 Foreign key 제약조건을 만족하지 않았을 때 발생하는 에러입니다. 또한 java spring boot를 실행했을때 실행이 되지 않는건 아닌데, 실행 창에 경고식으로 나타난다.

Caused by: java.sql.SQLException: Failed to add the foreign key constraint. Missing column 'user_id' for constraint '**' in the referenced table 'user_tb'

https://stackoverflow.com/questions/43511183/mysql-error-1822-failed-to-add-foreign-key-constraint-missing-index-for-contra

 

MySQL Error 1822: Failed to add foreign key constraint; missing index for contraint BUT index exists

I am trying to add an foreign key to my flightschedule table but it fails, but I do not really know why. The foreign key should reference the txtAC_tag attribute from the tblAircraft table which is...

stackoverflow.com

 

Foreign Key관계의 경우 관계를 만드는 상위 테이블은 Unique 하거나 Primary 이어야  합니다.

 

참조하고자 하는 값을 Primary Key로 지정하거나 Unique로 설정하면 에러가 해결될 것 입니다.

 

저의 해결 방법은 이렇게 table 어노테이션을 추가해서 해결했습니다.

@Table(uniqueConstraints = {
        @UniqueConstraint(name = "User_tb", columnNames = {"user_id"})
})