“无法添加外键约束";在Spring Data JPA上 [英] "Cannot add foreign key constraint" on Spring Data JPA

查看:120
本文介绍了“无法添加外键约束";在Spring Data JPA上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试执行我的spring boot项目时,我在标题上收到错误消息.我知道这是一个MySQL错误,但我不想在MySQL开发中处理创建和更改表的问题.这是在我的项目中执行的MySQL命令:

When I try to execute my spring boot project, I get the error message on the title. It is an MySQL error, I know but I do not want to deal with creating and altering the table on MySQL development. Here is the MySQL command executed in my project:

alter table password_reset_token add constraint FK5lwtbncug84d4ero33v3cfxvl foreign key (user_id) references user (id);

我有USER类和表;

I have USER class and table;

@Entity
@Table(name="USER")
public class User{
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String email;

  //Getters and Setters
}

我有一个实体;

@Entity
public class PasswordResetToken{

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String token;
  private User user;

  @OneToOne
  @JoinColumn(name="user_id")
  public User getUser(){
    return user;
  }
  //And other Getters and Setters
}

我在哪里弄错了?当我查看自动生成的表(password_reset_token)时,我看不到任何外键,并且当我运行该命令时,在MySQL开发方面也遇到了相同的错误.

Where do I make wrong? When I look at the table (password_reset_token) which is automatically generated, I do not see any foreign key and when I run the command, I get the same error on MySQL development side.

无法添加外键约束"的帖子很多,但就我而言,这些帖子都没有解决这个问题.

There are many "Cannot add foreign key constraint" posts but none of them addresses this problem in my case.

推荐答案

我找到了问题的原因.这是由于主键,外键的数据类型不匹配所致.

I found the cause of the problem. It is due to data type mismatch of primary key, foreign key.

我创建了用户"表,并用INT声明了它的主键.在User类中,我声明了'id'Long. JPA希望获得带有"BIGINT"的外键,但其类型实际上是"INT".这就是为什么,它给了我错误.我将类型更改为BIGINT,现在可以使用了.

I created 'User' table and declared its primary key with INT. In the User class, I declared 'id' Long. JPA expects to get foreign key with 'BIGINT' but its type is 'INT' actually. That is why, it gives me the error. I changed the type to BIGINT and now it works.

这篇关于“无法添加外键约束";在Spring Data JPA上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆