These are my Entities:-
This is my rider Rider entity
package com.app.enities;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
@Document(collection = "Rider")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(callSuper = true)
public class Rider {
@Id
private String id;
private String firstName;
private String lastName;
private String shortCred;
private Team teamName;
private List<Sponsor> sponsorList; //Enum
}
This is my team entity where I am adding information about a Team
package com.app.enities;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(callSuper = true)
public class Team {
@Id
private String id;
private String name;
private Bikes bike; //Enum
}
I am adding data in form of JSON. but as the id will get auto-generated, I am not providing any kind of Id:-
{
"firstName": "Marc",
"lastName": "Marquez",
"shortCred": "MM93",
"teamName": {
"name": "Gresini Racing",
"bike": "DUCATI"
},
"sponsorList": [
"REDBULL",
"SHOEI",
"ALPINESTAR",
"ESTRELLA_GALICIA",
"SAMSUNG"
]
}
But as you can see in the below response (which i have got in return after .save(newRider) method) That Rider id is getting auto generate but team id is not getting auto generate.
{
"id": "65c731de83a0e43d7526c880",
"firstName": "Marc",
"lastName": "Marquez",
"shortCred": "MM93",
"teamName": {
"id": null, <--- null value here
"name": "Gresini Racing",
"bike": "DUCATI"
},
"sponsorList": [
"REDBULL",
"SHOEI",
"ALPINESTAR",
"ESTRELLA_GALICIA",
"SAMSUNG"
]
}
This is first time I am using MongoDb with spring so I don’t know how association between tables work or that if it is even a thing to associate to table like we do in sql using @OneToOne or @ManyToOne etc.
2
Answers
According to me that is the expected behaviour.
"id" will be generated only for top level entity in case of MongoDB.
You can refer to the example provide here:
https://spring.io/blog/2021/11/29/spring-data-mongodb-relation-modelling
"id" is generated for "Book" but not for "Publisher".
If need the ids to be created you can use the @DBRef annotation as below:
You can use the @DBRef annotation for this if you want an autogenerated id in the nested object. That feature is part of spring-boot-starter-data-mongodb.