我正在努力对被引用对象进行Spring Boot MongoDB级联操作。下面是MongoDB文档架构类。
==发布
@Getter
@Setter
@Document(collection="Post") // (1)
public class Post {
@Id
private String _id;
@Indexed(unique = true)
private Long id;
private String title;
private String body;
private Date createdDate;
@DBRef(db = "User", lazy = true)
private User user;
@DBRef(db = "Tag", lazy = true)
private Collection<Tag> tags;
==用户
@Getter
@Setter
@Document(collection="User") // (1)
public class User {
@Id //(2)
private String _id;
@Indexed(unique = true)
private Long id;
@Indexed(unique=true) // (3)
private String username;
private String password;
private String email;
private String fullname;
private String role;
}
==标签
@Getter
@Setter
@Document(collection="Tag")
public class Tag {
@Id
private String _id;
@Indexed(unique = true)
private Long mid;
private String body;
private Date createdDate;
@DBRef(db = "User", lazy = true)
private User user;
}
但是@DBRef注释根本不起作用。它将引发以下异常。
2019-03-01 14:54:10.411 ERROR 5756 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.mapping.MappingException: Cannot create a reference to an object with a NULL id.] with root cause
org.springframework.data.mapping.MappingException: Cannot create a reference to an object with a NULL id.
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.createDBRef(MappingMongoConverter.java:975) ~[spring-data-mongodb-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writePropertyInternal(MappingMongoConverter.java:597) ~[spring-data-mongodb-2.1.4.RELEASE.jar:2.1.4.RELEASE]
将json文件导入MongoDB模式时,将显示上述错误。我发现使用谷歌搜索的一些参考文献site表示使用CascadingMongoEventListener类和用户定义的@CascadeSave注释生成新的事件源。但是我认为还有一些带有级联注释的解决方案。知道了吧。