我已經把兩個基本的類/表放在一起,以瞭解如何使用Hibernate。休眠關係外鍵約束失敗
一旦執行下面的代碼;
Session hbSession = HibernateUtil.getSession();
Showroom showroom = new Showroom();
showroom.setLocation("London");
showroom.setManager("John Doe");
List<Car> cars = new ArrayList<Car>();
cars.add(new Car("Vauxhall Astra", "White"));
cars.add(new Car("Nissan Juke", "Red"));
showroom.setCars(cars);
hbSession.beginTransaction();
hbSession.save(showroom);
hbSession.getTransaction().commit();
我得到這個錯誤;
Cannot add or update a child row: a foreign key constraint fails (`ticket`.`Car`, CONSTRAINT `FK107B4D9254CE5` FOREIGN KEY (`showroomId`) REFERENCES `Showroom` (`id`))
我不太確定它出錯的地方。這裏是兩個帶註釋的類;
@Entity
public class Showroom {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany
@JoinColumn(name="showroomId")
@Cascade(CascadeType.ALL)
private List<Car> cars = null;
private String manager = null;
private String location = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String color;
private int showroomId;
public Car(String name, String color) {
this.setName(name);
this.setColor(color);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getShowroomId() {
return showroomId;
}
public void setShowroomId(int showroomId) {
this.showroomId = showroomId;
}
}
暫時我讓Hibernate在MySQL數據庫中創建表。我已經檢查過並且數據庫之間的關係確實存在於Car表中。
有人能告訴我爲什麼這不起作用嗎?
我猜這是因爲陳列室沒有Id,因爲這是由MySQL自動生成的,所以汽車無法保存?是對的嗎?
所以,如果我先救展廳(不含汽車),確保我搶insertId並將此作爲id的陳列室,汽車再次添加到展廳和保存(更新),這應該插入有展廳ID的汽車? – SheppardDigital
查看本教程:http://alextretyakov.blogspot.hk/2013/07/jpa-many-to-many-mappings.html –
謝謝,我來看看。 – SheppardDigital