title: spring boot mongodb @dbref cascade not working
body: <p>I am struggling with Spring Boot MongoDB cascade operations on referenced objects. Below are MongoDB document schema classes.</p>
  
  <p><strong>== Post</strong></p>
  
  <pre><code>@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&lt;Tag&gt; tags;
  </code></pre>
  
  <p><strong>== User</strong></p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p><strong>== Tag</strong></p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>But @DBRef annotation does not work at all. It throws the following exception.</p>
  
  <pre><code>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]
  </code></pre>
  
  <p>When the json file is imported into MongoDB schema, the above error is shown.  I found some reference <a href="https://www.javacodegeeks.com/2013/11/spring-data-mongodb-cascade-save-on-dbref-objects.html" rel="nofollow noreferrer">site</a> 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.</p>