@DocumentReference 在保存时不会获取引用的文档

问题描述 投票:0回答:1

我创建了一个非常简单的案例,只是为了展示我的问题。我有以下实体:

@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 自动完成。这是正确的行为吗?知道我该如何改变吗?

java spring-boot spring-data-mongodb
1个回答
0
投票

如果我理解了你的问题,我认为这是正确的行为。

使用

@DocumentReference
不会保存引用的文档。检查这篇春季文章,我认为它显示了与您相同的示例:书籍和作者/出版商。

或者更简洁的这个春天参考其中说:

映射框架不处理级联保存,因此请确保单独保留引用的实体。

并解释与其他链接相同的示例。

顺便说一下,在绝大多数情况下,建议使用

@DocumentReference
lazy = true

© www.soinside.com 2019 - 2024. All rights reserved.