问题
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