I am trying to retrieve a list of entities using JpaRepository
's findAll()
method, but the Entity that I am trying to retrieve has a number of other Objects as OneToMany
Relationship inside it.
I have a class Program
as follows:
@Entity
public class Program extends BaseEntity {
private String programTitle;
private String description;
private String programType;
private String price;
@OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JsonManagedReference(value = "program-benefit")
private List<Benefit> benefits = new ArrayList<>();
@Column(name = "category")
private String category;
//Getters and setters
}
As you can see, It has a list of Benefits
in it.
When I am trying to retrieve Program, I am getting a JSON that has Both the objects list in it as well, Like:
Response I am getting:
{
"id":1,
"category": "cardio",
"description": "exercies for cardio",
"benefit": [
{
"description": "good for healt"
},
{
"description": "string2"
}
],
"price": "50",
"program_title": "cardio demo"
}
But I want a shallow copy of The object like
Expected Response:
{
"id":1,
"category": "cardio",
"description": "exercies for cardio",
"price": "50",
"program_title": "cardio demo"
}
I tried changing CascadeType
but it would stop showing nested objects in all APIs, I only want the nested objects to be removed when I call findAll()
method.
Is there a way to stop showing nested objects when I call the findAll()
method?
I see two choices:
If you want to avoid serializing the fetched fields, use
@JsonIgnore
.If you don't want to fetch those fields at all, create a DTO and write a custom query to map the results to it:
public class ProgramDTO { private Long id; private String programTitle; private String description; private String programType; private String price; }
And then:
entityManager .createQuery("select new ProgramDTO(p.id, p.programTitle, p.description, p.programType, p.price from Program p") .getResultList();