我已经把两个基本的类/表放在一起,以了解如何使用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