当我尝试删除记录时,我收到外键违规。
我有这个记录:
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long parentId;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "childId")
private Child child;
和
@Entity
@Table(name = "Child")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long childId;
public Long getOperatoryId() {
return id;
}
当我尝试删除孩子时,我会收到密钥违规,因为有一些父记录指向孩子。我想我可以先删除父级,然后删除子级为:
parentRepository.delete(parent)
但是我收到一个错误,即该属性ID并不存在于儿童身上。这是因为子ID被命名为childId而不是id?
答案 0 :(得分:0)
在这里,我研究了你要求的类似例子。根据您的需要定制它。
SQL Server表创建查询
CREATE TABLE "DBO"."Parent"(
Parent_Id INT PRIMARY KEY NOT NULL,
Parent_Name VARCHAR(255) NOT NULL)
CREATE TABLE "DBO"."Child"(
Child_Id INT PRIMARY KEY NOT NULL,
Child_Name VARCHAR(255) NOT NULL,
Parent_Ref_Id int not null,
CONSTRAINT FK_Parent_Ref_Id FOREIGN KEY (Parent_Ref_Id) REFERENCES Parent(Parent_Id)
)
Spring数据JPA代码
@Entity(name = "Parent")
@Table(name = "Parent")
public class Parent {
@Id
@Column(name = "Parent_Id")
private long parentId;
@Column(name = "Parent_Name")
private String parentName;
//cascade = {CascadeType.REMOVE} OR orphanRemoval = true
@OneToOne(cascade = {CascadeType.ALL},orphanRemoval = true,fetch = FetchType.LAZY,mappedBy="parentInfo")
private Child childInfo;
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Child getChildInfo() {
return childInfo;
}
public void setChildInfo(Child childInfo) {
this.childInfo = childInfo;
}
}
@Entity(name = "Child")
@Table(name = "Child")
public class Child {
@Id
@Column(name = "Child_Id")
private int childId;
@Column(name = "Child_Name")
private String childName;
@OneToOne
@JoinColumn(name = "Parent_Ref_Id", referencedColumnName = "Parent_Id")
private Parent parentInfo;
public int getChildId() {
return childId;
}
public void setChildId(int childId) {
this.childId = childId;
}
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
public Parent getParentInfo() {
return parentInfo;
}
public void setParentInfo(Parent parentInfo) {
this.parentInfo = parentInfo;
}
}
public interface ChildRepo extends CrudRepository<Child,Long> {
}
public interface ParentRepo extends CrudRepository<Parent,Long> {
Parent findByParentId(long id);
}
@Autowired
private final ParentRepo parentRepo;
....
private void save() {
//Save the parent
Parent p = new Parent();
p.setParentId(1);
p.setParentName("Parent1");
Child c = new Child();
c.setChildId(1);
c.setChildName("Child1");
c.setParentInfo(p);
p.setChildInfo(c);
parentRepo.save(p);
//delete the parent and child as well
Parent p1 = parentRepo.findByParentId(1);
parentRepo.delete(p1);
}