java - 如何使用 java spring 注释在 MongoDB 中创建完全填充的引用对象

标签 java mongodb spring-boot spring-data-jpa

当我将相同的对象添加到 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/

相关文章:

spring-boot - 应用程序类中的@ComponentScan 中断@WebMvcTest 和@SpringBootTest

Spring Javaconfig bean间依赖关系

java - InputStream类型的System.in是如何初始化的?

java - IntelliJ IDEA 中的调试超时

node.js - NestJS:如何获取 Mongoose 实例进行健康检查?

c# - MongoDB 的存储库模式 : Where to initialize the Database

java - 玩框架路线

java - 如何检查 SQL 查询是否没有结果?

spring - 如何对整个集合的数组大小求和?

java - Spring应用程序Thymeleaf中的css问题