jsonspring-bootspring-mongodb

spring boot mongodb @dbref cascade not working


I am struggling with Spring Boot MongoDB cascade operations on referenced objects. Below are MongoDB document schema 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;

== User

@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;
}

== Tag

@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;
}

But @DBRef annotation does not work at all. It throws the following exception.

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]

When the json file is imported into MongoDB schema, the above error is shown. I found some reference site with googling which said to generate new event source using CascadingMongoEventListener class and user-defined @CascadeSave annotation. But I think there are another solutions with some cascade annotations. Any idea,please.


Solution

  • Mongo doesn't support the relationship between documents. Due to this cascade operation doesn't support in spring data mongo. you can do it in two manners.

    1) Make your own cascade handler(best way to do is to use spring event publisher) But it can also be done using custom handler without spring event see here.
    2) Make an explicit call to referenced DB for operation.