我创建了一个非常简单的案例,只是为了展示我的问题。我有以下实体:
@Data
@Builder
@Document("bookEntity")
public class BookEntity {
@Id
private String id;
private String title;
private String price;
@DocumentReference
private AuthorEntity author;
}
和作者实体
@Data
@Builder
@Document("authorEntity")
public class AuthorEntity {
@Id
private String id;
private String name;
private String surname;
}
我还使用 MongoRepository 通过 Spring 数据与 mongo db 进行交互
public interface BookMongoRepo extends MongoRepository<BookEntity, String> {
}
public interface AuthorMongoRepo extends MongoRepository<AuthorEntity, String> {
}
最后是服务
@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();
}
}
我的问题是:为什么 createBook() 中返回的 BookEntity 不包含引用的 AuthorEntity,而 fetchBook() 的响应包含它?
到目前为止,我对此解决方案的唯一解决方法是通过显式调用 fatchAuthor() 并传递结果来丰富 createBook() 上的 BookEntity 响应,这应该由 @DocumentReference 自动完成。这是正确的行为吗?知道我该如何改变吗?