我有以下“父类”:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
// Changes the dock widgets arrangement.
splitDockWidget(ui->dock1, ui->dock3, Qt::Orientation::Horizontal);
splitDockWidget(ui->dock1, ui->dock2, Qt::Orientation::Vertical);
}
我还有以下子类:
@Entity
@Table(name = "parent_table")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long parentId;
private String firstName;
private String lastName;
@OneToMany(mappedBy = "Parent", cascade = CascadeType.ALL)
List<Child> children;
}
我在邮递员中发送以下请求:
@Entity
@Table(name = "children")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long childId;
@ManyToOne
@JoinColumn(name="parent_id")
private Parent parent;
private String name;
}
当我要求父级存储库保存父级时,它会保存,但是对于子级却什么也没有发生……它根本不会保存到数据库中……
作为参考,这是我保存父级的行
{
"firstName": "Test",
"lastName": "Parent",
"children":[{
"name":"jack"
},
{
"name":"jill"
}
]
}
(在这种情况下,父级内部有两个子级-但不会保存到子级表中)。
答案 0 :(得分:0)
我运行了您的示例,它似乎运行正常,唯一改变的只是mappedBy
批注的@OneToMany
属性。它必须是小写的。
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<Child> children = new ArrayList<>();
父母
@Entity
@Table(name = "parent_table")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "parent_id")
private Long parentId;
private String firstName;
private String lastName;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<Child> children = new ArrayList<>();
}
孩子
@Entity
@Table(name = "children")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long childId;
@ManyToOne
@JoinColumn(name="parent_id")
private Parent parent;
private String name;
}
测试
以上代码使下一个单元格成功:
@Test
public void parentRepositoryMustPersistParentAndChildren() {
Parent parent = new Parent("Anakin", "Skywalker");
parent.getChildren().add(new Child("Luke"));
parent.getChildren().add(new Child("Leia"));
Parent saved = parentRepository.save(parent);
Assert.assertNull("Parent does not have and id assigned after persist it", saved.getParentId());
saved.getChildren().forEach((child) ->{
Assert.assertNull("Parent does not have and id assigned after persist it", child.getChildId());
});
}