I’m creating a springboot microservices, with java, and spring-data-jpa. The idea is to create the repository with a dynamic select passing the fields to select from RequestParam, in runtime. Therefore, we’ll receive the fields in a List (“field1′,’field2′,’field3′), and we’ll select thsese fields from the entity. Of course, these fields can be change in every call.
I’ve found some ways, like “Query by example” and ‘project’ functionality, but it is selecting all the fields on the entity and not only the ones I need.
You can find an example here.
` @Test
void testFindByFirstWithConfederation() {
Example countryExample = buildRepublicExample();
Country firstRepublic = countryRepository.findBy(countryExample,
q -> q.sortBy(Sort.by("name"))
.project("confederation")
.firstValue());
assertThat(firstRepublic.getConfederation().getName()).isEqualTo(AFC_NAME);
}
It should get only 'confederation' field, but instead of it, it is selecting all the fields :
2024-05-22T09:50:34.051+02:00 DEBUG 15988 — [ main] org.hibernate.SQL : select c1_0.id,c1_0.capital,c2_0.id,c2_0.name,c1_0.name,c1_0.oecd,c1_0.population,c1_0.united_nations_admission from countries c1_0 left join confederations c2_0 on c2_0.id=c1_0.confederation_id where lower(c1_0.name) like ? escape ” order by c1_0.name fetch first ? rows only
`
Is it the expected behaviour? are there any way to make a select (the fields, not the where clause) in a dynamic way?