spring-projects / spring-projects/spring-data-rest

Spring data rest mongo adding entry to empty Reference fails

Open
#2,032 0 comments 0 reactions 1 assignee View on GitHub

@odrotbohm is already working on this.

Since Jan 4, 2022.

status: waiting-for-triage
Dominant language
Java
Stars
958
Forks
568
PR merge metrics
No merged PRs in 30d

Description

Mongo DB entity:

@Document
public class Person {
  @Id
  private ObjectId id;
  @DBRef
  private List<Account> accounts;
}

When using POST + uri to add an account:

java.lang.NullPointerException: Cannot invoke "java.util.Collection.add(Object)" because "collection" is null
	at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.lambda$createPropertyReference$10(RepositoryPropertyReferenceController.java:269) ~[spring-data-rest-webmvc-3.3.4.RELEASE.jar:3.3.4.RELEASE]
	at org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.lambda$doWithReferencedProperty$18(RepositoryPropertyReferenceController.java:403) ~[spring-data-rest-webmvc-3.3.4.RELEASE.jar:3.3.4.RELEASE]
	at java.base/java.util.Optional.map(Optional.java:258) ~[na:na]

https://github.com/spring-projects/spring-data-rest/blob/4c35f36598aaf35f5c70b6d7f70b90c8a9b75925/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java#L268

Happens because accounts is null.

In my opionion: Instead should create a new collection if previous value was null.
https://github.com/spring-projects/spring-data-rest/blob/4c35f36598aaf35f5c70b6d7f70b90c8a9b75925/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java#L262
https://github.com/spring-projects/spring-data-rest/blob/4c35f36598aaf35f5c70b6d7f70b90c8a9b75925/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryPropertyReferenceController.java#L263
Maybe something like:

AUGMENTING_METHODS.contains(requestMethod) && prop.propertyValue != null ? (Collection<Object>) prop.propertyValue : CollectionFactory.createCollection(propertyType, 0);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.