I am having 2 entities namely Project
and File
in SpringBoot. The structure of those entity is as given below.
@Document(collection="project")
public class Project{
@Id
private String id;
@Field("name")
private String name;
@Field("files")
@DBRef
@JsonIgnore
private List<File> files;
}
@Document(collection="file")
public class File{
@Id
private String id;
@Field("name")
private String name;
@Field("project")
@DBRef
private Project project;
}
Now when I am creating an object of Project
entity, saving it in database and fetching it again from the database using the Repository and trying to use equals
method it is returning false
.
When I checked individually for each attribute it was failing for the List<File> files
which is present in the Project
. But it is understandable that it will fail because the equals
method of File
class will only return true
if each of it's data member will satisfy equals
but as the File
have a reference to Project
, it will fail.
So this is kind of creating a loop.
If I override the equals
method of Project
to as given below, it works, but at the cost of neglecting the List<File> file
.
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Project))
return false;
if(this == obj)
return true;
Project that = (Project) obj;
return
this.id.equals(that.id) &&
this.name.equals(that.name);
}
How to solve this problem taking into consideration of the list of files as well?
CodePudding user response:
You can override the equals method and, check for equality of list just by matching the id's of the list objects in a different method. Or maybe you can use containsAll() to check for list elements equality. This is not a perfect solution but still checks for the list elements instead of completely ignoring them.
Also checkout circular dependency here and try to structure those entities in a different way:
https://www.baeldung.com/circular-dependencies-in-spring
CodePudding user response:
Try to save just Project.id in File. I'm assuming you need that just for reference. Compare the usecase, how often you'll need to find project from file or file from project and accordingly save.