更新时,拥有实体实例不再引用具有cascade =“all-delete-orphan”的集合

时间:2017-09-25 09:27:16

标签: java spring hibernate jpa thymeleaf

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; }

我在更新项目时遇到错误(仅更新名称)。 已经在互联网上寻找解决方案,但没有找到适合我的人。

1 个答案:

答案 0 :(得分:3)

我会尝试下列其中一项或全部内容:

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