简体   繁体   中英

How to save document with DBRef in mongodb spring-data

I have Spring data repository class that extends MongoRepository. So I'm doing a POST request to create a record that holds several reference fields to refer other documents.

The repository interface:

@RepositoryRestResource(collectionResourceRel = "user",path = "user")
 public interface UserRepository extends MongoRepository<User,String>{
}

The Model classes:

@Document(collection = "user")
public class User {
@Id
private String id;
private String email;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
@Field("infoSignups")
@DBRef
private InfoSignUp infoSignups;
@Field("webinarSignups")
@DBRef
private WebinarSignUp webinarSignups;

}

@Document(collection = "infoSignups")
public class InfoSignUp {

@Id
private String id;
private String email;

}

@Document(collection = "webinarSignups")
public class WebinarSignups {

@Id
private String id;
private String email;

}

The POST request:

{  
  "email":"sheen.example@gmail.com",
  "name":"test",
  "infoSignups":[  
    {  
     "id":"5cbeb33199a4640b94ba1de8"
     }
   ],
  "webinarSignups":[  
    {  
     "id":"5cc0136599a4641d835d3259"
    }
   ],
  "businessName":"test data",
  "phone":"test data",
  "address":"test data",
  "createdTime":"2015-09-26T01:30:00.000Z"
 }

But when I'm doing the POST request to the repository endpoint the reference fields are not saved, other fields are saved in the collection. Do I have to persist the object manually without using the Spring data? How can I save the references to the other collection using the POST request to the endpoint?

Before version 3.3.0 of Spring Data MongoDB we need to retrieve the linked document on the base of Id and set that value.

If you are using the version number 3.3.0 or newer you can directly use the annotation @DocumentReference instead of @DBRef

For more details you can visit the https://bootify.io/mongodb/document-reference-in-spring-boot-mongodb.html

or

https://docs.spring.io/spring-data/mongodb/docs/3.4.0-M4/api/org/springframework/data/mongodb/core/mapping/DocumentReference.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM