私はこの状況を持っています:
@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>();
たとえば状況で
Project_A と ProjectLeader_1 および Project_B と ProjectLeader_2
ProjectLeader_1 を Project_B に追加しようとすると、ProjectLeader_1 が Project_A から Project_B に完全に移動されるため、次のような状況になります。
Project_A with -No Leader- and Project_B with ProjectLeader_2 ProjectLeader_1
望ましい結果は次のようになります。
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;
}
これの潜在的な理由は何ですか?
私はここに新しいので、他の場所に同様の質問がある場合はリンクを投稿してください。ありがとうございました。