我有一个运行Hibernate ORM的ejb模块,我有两个POJO用于模型, 这里是第一堂课:
@Entity
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
public Vehicle() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
这是我的第二堂课:
@Entity
public class Transfer implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Vehicle vehicle;
public Transfer() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToOne
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
}
现在,当我尝试删除Vehicle v1实例时出现此错误:
Cannot delete or update a parent row: a foreign key constraint fails (`pallasmobiledb`.`transfer`, CONSTRAINT `FK_9u0s4qxviu868ir3r7sgtbuqa` FOREIGN KEY (`cpo_id`) REFERENCES `user` (`id`))
有人会说我的映射机制有错吗?
答案 0 :(得分:0)
当移除车辆时,由于它是一对一的映射,传输对象也将被删除。 您正在删除“Vehicle”实体,并且您的一对一处于“转移”状态。 有两种方法:
1 - 删除车辆前删除转移对象。
2 - 您需要将删除级联到另一个实体。像这样注释你的@OneToOne:
@OneToOne(cascade = CascadeType.ALL)
但是“车辆”实体......您必须更改映射