为什么我不能在这里创建一个外键? ERROR 1215(HY000):无法添加外键约束

时间:2017-12-06 20:23:25

标签: java mysql jpa

我不确定我在这里做错了什么我已经阅读了规范但仍然无法弄明白。我想将用户ID作为forign键添加到我的商店表中但我一直收到错误1215。

我的sql代码:

CREATE TABLE Store (
id int,
storePersistentId varchar(255),
storename varchar(255),
user_id int,
PRIMARY KEY (id),
FOREIGN KEY (user_id) 
    REFERENCES user(id)
);

Store.java

@Entity
public class Store {

//every entity requires an id, and we can make it auto generated
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String storePersistentId;
private String storename;

@ManyToOne
public User user;

public Store(User user,String storePersistentId){

}

public Store(){

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getStorename() {
    return storename;
}

public void setStorename(String storename) {
    this.storename = storename;
}

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

public String getStorePersistentId() {
    return storePersistentId;
}

public void setStorePersistentId(String storePersistentId) {
    this.storePersistentId = storePersistentId;
}


}

User.java

@Entity
public class User {

@Id
@Column
private int id;

private String username;
private String password;


public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}


public User() {
}
}

任何帮助都会很棒。 它可能是一些小错误,但我需要另一组眼睛来检查它。

1 个答案:

答案 0 :(得分:0)

mysql> create table store(id int primary key NOT NULL AUTO_INCREMENT,
username varchar(255), 
password varchar(255),
user_id int, foreign key(user_id) 
references user(id));

最终得到它。