当我将相同的对象添加到 MongoDB 表的数组中的表中时,出现主要唯一约束错误。我真的想要数组中的整个对象,而不仅仅是对其的引用。
好的,我有这样的情况,我有一个图书表,其中有很多图书,每本书都有一个 id 作为唯一的主键。
图书表:
{
"_id" : "1234-sc-myKey",
"title" : "Tom Sawyer",
"author" : "Mark Twain"
}
然后我有一个存储表:
{
"_id" : "myStoreId-1",
"name" : "book store 1",
"books" : [
{
"_id" : "1234-sc-myKey",
"title" : "Tom Sawyer",
"author" : "Mark Twain"
},
{
"_id" : "5678-pc-myKey",
"title" : "Huck Finn",
"author" : "Mark Twain"
}
]
}
当我将同一本书添加到另一个商店时,出现主键约束错误。我知道我可以做这个注释 @DBRef 并使存储表看起来像这样:
{
"_id" : "myStoreId-1",
"name" : "book store 1",
"books" : [
{
"$ref" : "Book",
"$id" : "1234-sc-myKey"
}
}
但随后我必须再次查询数据库以获取每本书的书名列表。有没有办法让书在商店表中,同时在书上有一个唯一的主键?我确信有一个很酷的 java spring 注释,但我没有找到它。
Java 信息:
类(class)书籍
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Document(collection = "Book")
@CompoundIndexes({
@CompoundIndex(name = "pk_idx", def = "{'bookId':1, 'type': 1, 'myKey': 1}", unique=true)
})
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Book {
@Id
private String id;
etc...
}
类商店:
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Document(collection = "Store")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Store {
@Id
private String id;
private String name;
//this is the solution where it throws unique constraint
private List<Book> books;
//this is the solution I don't like
@DBRef
private List<Book> books;
}
最佳答案
尝试添加@Reference
以上private List<Book> books;
上课Store
关于java - 如何使用 java spring 注释在 MongoDB 中创建完全填充的引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029197/