我有这种情况:
@Entity
@Table(name = "project_leader")
public class ProjectLeader {
@ManyToOne
@JoinColumn(name = "projectId")
@JsonBackReference(value = "project")
private Project project;
...
及相关实体
@Entity
@Table(name = "project")
public class Project {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "project", orphanRemoval = true)
@Cascade(CascadeType.ALL)
@JsonManagedReference(value = "project")
private Set<ProjectLeader> projectLeaders = new HashSet<ProjectLeader>();
例如在情况下
带有 ProjectLeader_1 的 Project_A 和带有 ProjectLeader_2 的 Project_B
当我尝试将 ProjectLeader_1 添加到 Project_B 时,我也将 ProjectLeader_1 从 Project_A 完全移动到 Project_B,所以我有以下情况:
带有 -No leader- 的 Project_A 和带有 ProjectLeader_2 ProjectLeader_1 的 Project_B
理想的结果应该是:
Project_A 与 ProjectLeader_1 和 Project_B 与 ProjectLeader_2 ProjectLeader_1
以下是为项目分配领导者的方法:
private Project initializeProject(@Nonnull ProjectDto projectDto) {
Project project = null;
if (projectDto.getId() != null) {
project = projectRepository.findOne(projectDto.getId());
} else {
project = new Project();
}
project.setName(projectDto.getName());
project.setProjectType(projectDto.getProjectType());
project.setFinancedBy(projectDto.getFinancedBy());
Set<ProjectLeader> projectLeaders = new HashSet<ProjectLeader>();
for (ProjectLeaderDto projectLeaderDto : projectDto.getProjectLeaderDtos()) {
ProjectLeader projectLeader = new ProjectLeader();
Professor professor = null;
if (projectLeaderDto.getId() != null && projectLeaderDto.getId() > 0L) {
projectLeader = projectLeaderRepository.findOne(projectLeaderDto.getId());
}
if (projectLeaderDto.getProfessorId() != null && projectLeaderDto.getProfessorId() > 0L) {
professor = professorRepository.findOne(projectLeaderDto.getProfessorId());
}
projectLeader.setName(projectLeaderDto.getName());
projectLeader.setSurname(projectLeaderDto.getSurname());
projectLeader.setProject(project);
projectLeader.setProfessor(professor);
projectLeaders.add(projectLeader);
}
// If collection from Dto miss some element from original collection, we
// remove it from original
Iterator<ProjectLeader> currentLeadersIterator = project.getProjectLeaders().iterator();
while (currentLeadersIterator.hasNext()) {
ProjectLeader projectLeader = currentLeadersIterator.next();
if (!projectLeaders.contains(projectLeader)) {
currentLeadersIterator.remove();
projectLeader.setProject(null);
}
}
// If original collection miss some element from Dto collection, we add
// it to original
Iterator<ProjectLeader> newLeadersIterator = projectLeaders.iterator();
while (newLeadersIterator.hasNext()) {
ProjectLeader projectLeader = newLeadersIterator.next();
if (!project.getProjectLeaders().contains(projectLeader)) {
project.getProjectLeaders().add(projectLeader);
projectLeader.setProject(project);
}
}
return project;
}
这可能是什么潜在原因?
我是新来的,所以如果其他地方有类似的问题,请给我发一个链接。谢谢你。