I’m working with Spring and MongoDB. I have a Folder class which has a list of subfolders and a list of files. I’m using DBRef which stores the reference id to the list objects instead of the whole object in the database.
When I submit a get request for the “root” folder I have, the returned json also has loaded the subfolders, their subfolder, and so on. This is bad because I’m getting data I dont need right away. I would only like to get the ids of the subfolders so that if i click on one, I submit an HTTP GET with that exact id.
package org.example.schoolioapi.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;
import java.util.List;
@Document(collection = "folders")
@Data
public class Folder {
@Id
private String id;
private String name;
@DBRef
private List<Folder> subFolders;
@DBRef
private List<Note> notes;
public Folder(String name) {
this.name = name;
this.subFolders = new ArrayList<>();
this.notes = new ArrayList<>();
}
public void addNote(Note note) {
if (this.notes == null) notes = List.of(note);
else notes.add(note);
}
public void addSubFolder(Folder subFolder) {
if (this.subFolders == null) subFolders = List.of(subFolder);
else subFolders.add(subFolder);
}
}
Example of Folder object in DB
What the API returns:
3
A quick solution is to annotate subFolders with @JsonIgnoreProperties
.
For example, if a Folder
class looks like below:
class Folder {
private String id;
private String name;
@JsonIgnoreProperties("subFolders")
private List<Folder> subFolders;
//constructor, getters and setters
}
and we initialize the root folder as follows:
Folder root = new Folder(
"0",
"root",
Arrays.asList(
new Folder("0-1", "sub-1", Arrays.asList(
new Folder("0-1-1", "sub-1-1", Collections.emptyList()),
new Folder("0-1-2", "sub-1-2", Collections.emptyList())
)),
new Folder("0-2", "sub-2", Arrays.asList(
new Folder("0-2-1", "sub-2-1", Collections.emptyList()),
new Folder("0-2-2", "sub-2-2", Collections.emptyList())
))
));
then after serializing root
with library Jackson
, output will only contain 1-st level of subFolders
:
p.s. other fields will still be serialized, need find some way to show the id
only.
{
"id" : "0",
"name" : "root",
"subFolders" : [ {
"id" : "0-1",
"name" : "sub-1"
}, {
"id" : "0-2",
"name" : "sub-2"
} ]
}
2