I have created a very simple case, just to show my question. I have the following entities:
@Data
@Builder
@Document("bookEntity")
public class BookEntity {
@Id
private String id;
private String title;
private String price;
@DocumentReference
private AuthorEntity author;
}
And the Author entity
@Data
@Builder
@Document("authorEntity")
public class AuthorEntity {
@Id
private String id;
private String name;
private String surname;
}
I'm also using MongoRepository to interact with the mongo db through Spring data
public interface BookMongoRepo extends MongoRepository<BookEntity, String> {
}
public interface AuthorMongoRepo extends MongoRepository<AuthorEntity, String> {
}
And finally the Services
@Service
@Transactional
@RequiredArgsConstructor
public class AuthorMongoDataStore {
private final AuthorMongoRepo repo;
public AuthorEntity createAuthor(AuthorEntity input) {
return repo.insert(input);
}
public AuthorEntity fetchAuthor(String id) {
return repo.findById(id).get();
}
}
@Service
@Transactional
@RequiredArgsConstructor
public class BookMongoDataStore {
private final BookMongoRepo repo;
public BookEntity createBook(BookEntity input) {
return repo.save(input);
}
public BookEntity fetchBook(String id) {
return repo.findById(id).get();
}
}
My question is: Why the returned BookEntity in the createBook() does not include the referenced AuthorEntity, while the response from the fetchBook() contains it?
My only workaround to this solution so far is to enrich the BookEntity response on the createBook() by calling the fatchAuthor() explicitly and passing the result, which should be done automatically by @DocumentReference. Is this the correct behavior? Any idea how can i change that?
EDIT: I create an AuthorEntity in the database BEFORE i save my BookEntity object. So i don't expect that my Referenced Object will be saved with the parent object. I'm just expecting that the save response, contains the referenced document in the same way the fetchBook() does.