Home Why cant i create a foreign key here? ERROR 1215 (HY000): Cannot add foreign key constraint
Reply: 1

Why cant i create a foreign key here? ERROR 1215 (HY000): Cannot add foreign key constraint

college1
1#
college1 Published in 2017-12-06 20:23:24Z

Im not sure what im doing wrong here i have read the spec but still cant figure it out.I want to add user id as a forign key to my store table but i keep getting error 1215.

My sql code:

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() {
}
}

Any help would be great. its probally some small mistake but i need another set of eyes to check it out please.

college1
2#
college1 Reply to 2017-12-06 21:49:21Z
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));

Got it eventually.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.321564 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO