目标
本文章主要介绍级联中的「插入」「查询」「删除」操作。
环境搭建
- Project.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@TableName("p_project")
public class Project extends BaseComponentEntity {
private String title;
private String description;
private Long ownerId;
private String coverUrl;
@ManyToOne(value = "project_group_id", parentTable = "p_project_group")
private ProjectGroup projectGroup;
}
@ManyToOne
是子表注解,它有2个属性,value
表示引用外键的字段名,parentTable
引用的父表名。
- ProjectGroup.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@TableName("p_project_group")
public class ProjectGroup extends BaseComponentEntity {
private String title;
@OneToMany(subTable = "p_project", reversePropertyName = "projectGroup", cascadeSaveOrUpdate = true)
private List<Project> projectList;
}
@OneToMany
是父表注解,属性是 List
集合。它有2个属性,reversePropertyName
表示子对象中该对象的属性名,subTable
关联的子表名。cascadeSaveOrUpdate
开启级联更新。
测试
级联插入
@Test
public void save() {
ProjectGroup projectGroup = ProjectGroup.builder().title("我的组").projectList(Lists.newArrayList(Project.builder().title("我的项目").ownerId(11L).build())).build();
projectGroupService.save(projectGroup);
Project project = Project.builder().title("我的项目-2").ownerId(11L).build();
project.setProjectGroup(projectGroup);
projectService.save(project);
}
projectGroupService.save 可以级联插入;projectService.save单个插入,但是属性需要关联对象 ProjectGroup
,需要对象中的 id 信息。
级联查询
@Test
public void select() {
ProjectGroup projectGroup = projectGroupService.getByTitle("我的组").get(0);
Assert.assertEquals("我的项目", projectGroup.getProjectList().get(0).getTitle());
Assert.assertEquals("我的项目-2", projectGroup.getProjectList().get(1).getTitle());
Project project = projectService.findById(486880981274755072L).get();
Assert.assertEquals("我的组", project.getProjectGroup().getTitle());
}
级联删除
@Test
public void deleteLogically() {
projectGroupService.deleteLogically(486678250836623360L);
Assert.assertEquals(false, projectService.findById(486678250924703744L).isPresent());
}
@Test
public void deleteHardly() {
projectGroupService.delete(486678250836623360L);
}