spring boot mongodb @dbref 级联不起作用

Jos*_*ang 1 json spring-boot spring-mongodb

我正在努力处理引用对象上的 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;
Run Code Online (Sandbox Code Playgroud)

== 用户

@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;
}
Run Code Online (Sandbox Code Playgroud)

== 标签

@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;
}
Run Code Online (Sandbox Code Playgroud)

但是@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]
Run Code Online (Sandbox Code Playgroud)

当json文件导入MongoDB schema时,出现上述错误。我通过谷歌搜索找到了一些参考站点,据说使用 CascadingMongoEventListener 类和用户定义的 @CascadeSave 注释生成新的事件源。但我认为还有另一种带有一些级联注释的解决方案。任何想法,请。

Nis*_*waz 5

Mongo不支持 之间的关系documents。由于spring data mongo不支持这种级联操作。你可以通过两种方式做到这一点。

1)创建自己的级联处理程序(最好的方法是使用spring event发布者),但也可以使用自定义处理程序而不需要 spring 事件来完成,请参阅此处
2) 显式调用引用的数据库进行操作。