我在ProjectRequirement实体之间有一对多的关系。

HTML:

<div class="container">
    <div class="row">
        <div class="col-sm-2"></div>
        <div class="col-sm-8">
            <form action="#" th:action="@{/projects/updateProject/(id=${project.id})}" method="post">
                <input hidden="hidden" name="id" th:value="${project.id}" />
                <div class="form-group">
                    <label>Project</label>
                    <input type="text" name="projectNaam" class="form-control" id="projectName" th:value="${project.projectName}" placeholder="Project"  />
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>

        </div>
        <div class="col-sm-2"></div>
    </div>
</div>

这是我的Project的控制器代码:
@RequestMapping(value = "/updateProject", method = RequestMethod.POST)
public String updateProject @ModelAttribute("project") Project project){
    this.projectService.saveProject(project);

    return "redirect:/projects";
}

这是我的Project类:
@Entity
@Table(name = "Project")
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String projectName;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "project_id")
    private Set<Requirement> requirements;

    public Project(){

    }

    public Project(String projectName) {
        this.projectName = projectName;
    }

    public Integer getId() {
        return id;
    }

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

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public Set<Requirement> getRequirements(){ return requirements; }

    public void setRequirements(Set<Requirement> requirements){ this.requirements = requirements; }

更新项目(仅更新名称)时出现错误。
已经在Internet上寻找一种解决方案,但找不到适合我的解决方案。

最佳答案

我会尝试以下一项或全部:

  • 您正在从事务上下文外部传递Project对象。保存前确保已合并。
  • 确保集合中的每个Requirement都引用了Project实体。
  • 确保合并后,您不使用public void setRequirements(Set<Requirement> requirements)方法。
  • 使用Set时。确保Requirement已正确实现hashCodeequals
  • 08-05 00:08