Currently I'm using Spring Data JPA 2.2.1 with a Spring Boot Web 2.2.1 for a REST API service.
A getter call to /categories returns the following JSON, which in fact is the desired result:
[
{
"category1": "A",
"category2": "B",
"subcategories": []
},
{
"category1": "A",
"category2": "B",
"subcategories": [{
"field1": "A",
"field2": "B",
"field3": "C",
"field4": "D"
}]
},
.........
.........
]
Entities:
@Entity
@Table(name = "category")
@Getter @Setter
public class Category {
@JsonIgnore
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String category1;
private String category2;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Subcategory> subcategories;
}
@Entity
@Table(name = "subcategory")
@Getter @Setter
public class Subcategory {
@JsonIgnore
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@JsonIgnore
private int parent;
private String field1;
private String field2;
private String field3;
private String field4;
}
Controller:
@RestController
public class MyController {
private final DataService dataService;
@Autowired
public MyController(DataService dataService) {
this.dataService = dataService;
}
@GetMapping("/categories")
public List<Category> getAllCategories() {
return dataService.getAllCategories();
}
Repository
public interface MyRepository extends JpaRepository<Category, Long> {
List<MyRepository> findAll();
}
DataService
@Component
public class DataService {
private MyRepository myRepository;
@Autowired
public DataService(MyRepository myRepository) {
this.myRepository = myRepository;
}
public List<Category> getAllCategories() { return myRepository.findAll(); }
I now want to add a new call to my API, /limitedCategories, which does not return all of the fields. For example, "category2" of the parent entity, and "field4" of the nested entity shall be excluded.
Problem:
- I don't manage to manually select the desired fields within my JPA Repository, and also wouldn't know how to deal with the nested object.
- The simple idea to just use findAll and exclude those fields using @JsonIgnore is not possible, as my first request still needs those fields.
- When using @Query annotation within my repository to fetch only the desired fields, I cannot find a way to fetch the nested fields for my JSON.
Thanks in advance.
I'm using Spring Data JPA 2.2.1 with a Spring Boot Web 2.2.1.