Spring Hibenate:通过REST更新ManyToMany关系

时间:2019-06-06 14:56:33

标签: spring hibernate spring-data-jpa spring-hateoas

我已经在REST,JPA和HATEOAS上进行了春季项目,我的UserProfile实体与ManyToMany实体具有Tag关联,如下所示


    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_profile_special_case_tag_assoc",
            joinColumns = { @JoinColumn(name = "user_profile_id")},
            inverseJoinColumns = { @JoinColumn(name = "tag_id")}
    )
    @RestResource(exported = false)
    private Set special_cases = new HashSet();

如果我通过REST列出了userProfiles实体,则它以Tag数组的形式出现,这是预期的。即


    {
      "special_cases": []
    }

我还可以插入或完全删除与PATCH请求的关联,即PATCH http://localhost/userProfile/1


    {
      "special_cases": [
        {
          "tagId": 1
        },
        {
          "tagId": 2
        },
        {
          "tagId": 3
        }
      ]
    }

或完全删除关联,即PATCH http://localhost/userProfile/1


    {
      "special_cases": []
    }

但是,如果我尝试部分更改关联,则会出现异常。即


    {
      "special_cases": [
        {
          "tagId": 2
        },
        {
          "tagId": 3
        }
      ]
    }

但是我得到


    {
        "timestamp": "2019-06-06T14:29:08.960+0000",
        "status": 500,
        "error": "Internal Server Error",
        "message": "identifier of an instance of Tag was altered from 1 to 2; nested exception is org.hibernate.HibernateException: identifier of an instance of Tag was altered from 1 to 2",
        "path": "/userProfiles/1"
    }

我的理解是Hibernate尝试重用ID为1的嵌套Tag实体,并尝试将主键更新为2。因此是异常。我该如何预防?

有人可以在春季帮助使用REST和HATEOAS来实现部分关联更改的资源吗?

我想知道是否有一种方法可以告诉hibernate删除所有关联并在更新时重新插入它们。

0 个答案:

没有答案