如何在Spring Data MongoDB中工作@DocumentReference



我有两个实体:Publisher和Book。

@Document(collection = "publishers")
data class Publisher(
@MongoId(value = FieldType.OBJECT_ID) 
val id: ObjectId? = null,
@DocumentReference(lazy = true)
val books: MutableList<Book>,
val name: String? = null,
val arconym: String? = null,
val foundationYear: Int? = null
)

@Document(collection = "books")
data class Book(
@MongoId(value = FieldType.OBJECT_ID) val id: ObjectId? = null,
val isbn13: String? = null,
val title: String? = null,
val pages : Int? = null,
)

我要查找包含标题为"Title1"的图书的出版商集合中的所有出版商。我正在运行此请求,但得到空列表:

@GetMapping("/find")
fun findPublishers(): MutableList<Publisher> {
return mongoTemplate.find(
Query().addCriteria(
Criteria.where("books").elemMatch(
Criteria.where("title").`is`("Title1")
)
), Publisher::class.java
)
}

我发现这是因为@DocumentReference中的(lazy = true)。所以,如果我不使用"lazy = true", MongoDB保存所有字段的图书在出版商的集合,我的请求工作正常。

我想把这样的书保存在出版商的ID集合中,希望我的请求能起作用。

我想保存结果在MongoDB像这样

请帮我一下,如果可能的话?我在这里建立了信息https://spring.io/blog/2021/11/29/spring-data-mongodb-relation-modelling

所以我想添加请求"mongoTemplate.findAll(Publisher::class.java)"无论如何都能正常工作。

我还没有找到使用Spring Data MongoDB的解决方案,但使用MongoJack很容易解决:

<!-- https://mvnrepository.com/artifact/org.mongojack/mongojack -->
<dependency>
<groupId>org.mongojack</groupId>
<artifactId>mongojack</artifactId>
<version>4.5.0</version>
</dependency>
  1. 创建带有链接的实体DBRef:

    @MongoCollection(name = "publishers")
    data class Publisher(
    @MongoId(value = FieldType.OBJECT_ID) 
    val id: ObjectId? = null,
    @DocumentReference(lazy = true)
    val books: MutableList<DBRef<Book, ObjectId>>,
    val name: String? = null,
    val arconym: String? = null,
    val foundationYear: Int? = null
    )
    
  1. 按Id查找出版商

    val publisher: Publisher = collectionOfPublishers.findOne(Filters.eq("_id", ObjectId("62acbc0f51df607f29896c3c")))

  2. 查找出版商的图书:

.

val dbReferenceManager: DbReferenceManager = DbReferenceManager(
mongoClient, "publishers", UuidRepresentation.STANDARD
)

val booksOfPublisher = dbReferenceManager.fetch(book.articles)

它的工作方式是:如果有必要,我们可以按书查找出版商

更多信息:https://mongojack.org/dbrefs.html

最新更新