JPA和Hibernate持续@manytoOne关系

时间:2015-05-24 10:55:19

标签: java jpa many-to-many one-to-many hibernate-cascade

我遇到这种情况:

@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>();

在情况中例如

项目_A与ProjectLeader_1和 带有ProjectLeader_2的Project_B

当我尝试将ProjectLeader_1添加到Project_B时,我也将ProjectLeader_1从Project_A完全移到Project_B,因此我遇到以下情况:

Project_A与-No leader-和 Project_B with ProjectLeader_2 ProjectLeader_1

理想的结果应该是:

项目_A与ProjectLeader_1和 Project_B with 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;
    }

这可能是什么原因?

我是新来的,如果其他地方有类似的问题,请给我发一个链接。 谢谢。

1 个答案:

答案 0 :(得分:1)

我认为插入时存在问题,请注意每个项目都有一个项目负责人,所以如果你把另一个项目负责人放到项目中,那么旧项目将被删除,新项目将被插入,我写了关于你的问题的小程序:

package leader;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the Project database table.
* 
*/
@Entity
@NamedQuery(name="Project.findAll", query="SELECT p FROM Project p")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private int id;

//bi-directional many-to-one association to ProjectLeader
@ManyToOne
@JoinColumn(name="Leader_Id")
private ProjectLeader projectLeader;

public Project() {
}

public int getId() {
    return this.id;
}

public void setId(int id) {
    this.id = id;
}

public ProjectLeader getProjectLeader() {
    return this.projectLeader;
}

public void setProjectLeader(ProjectLeader projectLeader) {
    this.projectLeader = projectLeader;
}

}

ProjectLeader类:

package leader;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;



@Entity
@NamedQuery(name="ProjectLeader.findAll", query="SELECT p FROM ProjectLeader p")
 public class ProjectLeader implements Serializable {
 private static final long serialVersionUID = 1L;

@Id
private int id;

//bi-directional many-to-one association to Project
@OneToMany(mappedBy="projectLeader",fetch=FetchType.EAGER,orphanRemoval=true)
private List<Project> projects;

public ProjectLeader() {
}

public int getId() {
    return this.id;
}

public void setId(int id) {
    this.id = id;
}

public List<Project> getProjects() {
    return this.projects;
}

public void setProjects(List<Project> projects) {
    this.projects = projects;
}

public Project addProject(Project project) {
    getProjects().add(project);
    project.setProjectLeader(this);

    return project;
}

public Project removeProject(Project project) {
    getProjects().remove(project);
    project.setProjectLeader(null);

    return project;
}

}

和测试类

package leader;

 import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;

public class Test {

@PersistenceUnit(unitName="leader")
EntityManagerFactory emf1;


  public static void main(String[] args) {
    Project projectA = new Project();
    projectA.setId(1);


    Project projectB = new Project();
    projectB.setId(2);


    ProjectLeader leaderA = new ProjectLeader();
    leaderA.setId(1);

    ProjectLeader leaderB = new ProjectLeader();
    leaderB.setId(2);



    EntityManagerFactory emf =    Persistence.createEntityManagerFactory("leader");
    EntityManager em=emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(leaderA);
    em.persist(leaderB);

   // projectA.setProjectLeader(leaderA);
    projectA.setProjectLeader(leaderB);

    projectB.setProjectLeader(leaderA);
   // projectB.setProjectLeader(leaderB);


    em.persist(projectA);
    em.persist(projectB);
    em.getTransaction().commit();



  }

}