How to properly add an element to a collection using JSONPatch with Spring Data REST?

自闭症网瘾萝莉.ら 提交于 2019-12-09 06:32:20

问题


I have a very simple Spring Data REST project with two entities, Account and AccountEmail. There's a repository for Account, but not for AccountEmail. Account has a @OneToMany relationship with AccountEmail, and there is no backlink from AccountEmail.

Update: I believe this to be a bug. Filed as DATAREST-781 on Spring JIRA. I included a demo project and instructions to duplicate there.

I can create an Account using the following call:

$ curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"emails":[{"address":"nil@nil.nil"}]}' \ 
  http://localhost:8080/accounts

Which returns:

{
  "emails" : [ {
    "address" : "nil@nil.nil",
    "createdAt" : "2016-03-02T19:27:24.631+0000"
  } ],
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/accounts/1"
    },
    "account" : {
      "href" : "http://localhost:8080/accounts/1"
    }
  }
}

I then attempt to use JSONPatch to add another email address to that account:

$ curl -X PATCH \
   -H "Content-Type: application/json-patch+json" \
   -d '[{ "op": "add", "path": "/emails/-","value":{"address":"foo@foo.foo"}}]' \
   http://localhost:8080/accounts/1

Which adds a new object to the collection, but the address is null for some reason:

{
  "emails" : [ {
    "address" : null,
    "createdAt" : "2016-03-02T19:30:06.417+0000"
  }, {
    "address" : "nil@nil.nil",
    "createdAt" : "2016-03-02T19:27:24.631+0000"
  } ],
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/accounts/1"
    },
    "account" : {
      "href" : "http://localhost:8080/accounts/1"
    }
  }
}

Why is the address of the newly added object null? Am I going about this wrong? Any tips appreciated.

I am using Spring Boot 1.3.2.RELEASE and Spring Data Gosling-SR4. Backing database is HSQL.

Here are the entities in question:

@Entity
public class Account {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(cascade = CascadeType.PERSIST)
    private List<AccountEmail> emails = Lists.newArrayList();

}

@Entity
public class AccountEmail {

    @Id
    @GeneratedValue
    private Long id;

    @Basic
    @MatchesPattern(Regexes.EMAIL_ADDRESS)
    private String address;

    @CreatedDate
    @ReadOnlyProperty
    @Basic(optional = false)
    @Column(updatable = false)
    private Date createdAt;

    @PrePersist
    public void prePersist() {
        setCreatedAt(Date.from(Instant.now()));
    }

}

来源:https://stackoverflow.com/questions/35756753/how-to-properly-add-an-element-to-a-collection-using-jsonpatch-with-spring-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!