spring 启动 mongodb @dbref 级联不工作

spring boot mongodb @dbref cascade not working

我正在为引用对象的 Spring 引导 MongoDB 级联操作而苦苦挣扎。以下是 MongoDB 文档架构 classes.

== Post

@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 class 和用户定义的 @CascadeSave 注释生成新的事件源。但我认为还有另一种带有级联注释的解决方案。有什么想法,请。

Mongo 不支持 documents 之间的关系。由于此级联操作在 spring 数据 mongo 中不支持。您可以通过两种方式进行。

1) 制作您自己的级联处理程序(最好的方法是使用 spring event 发布者)但它也可以使用没有 spring 事件 see here 的自定义处理程序来完成。
2) 显式调用引用DB进行操作。

看看 RelMongo,它是一个构建在 Spring 数据之上的框架,它可以实现级联、获取......甚至是 DBRefs 无法实现的查找