0
I am making a findAll using Jparepository and Exemple (Examplematcher).
Entity Cidade
public class City implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
@Column(nullable = false)
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "UFSTATE", nullable = false, referencedColumnName = "UF")
private State state;
}
Entity Estado
public class State implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, length = 2)
private String uf;
}
Repository
@Repository
public interface CityRepository extends JpaRepository<City, Long> {
@Override
@Query("FROM City c JOIN FETCH c.state")
List<City> findAll();
}
Service
@Service
public class CityService {
@Autowired
private CityRepository cityRepository;
public List<City> findAllWithFilters(City filtro) {
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreCase()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
return cityRepository.findAll(Example.of(filtro, matcher));
}
}
Controller
@RestController
@RequestMapping("/cities")
public class CityController {
@Autowired
private CityService cityService;
@GetMapping
public List<City> findAllWithFilter(City filtro) {
return cityService.findAllWithFilters(filtro);
}
}
When I perform the flame in the API localhost:8080/cities
right back:
[
{
"id": 110001,
"name": "Alta Floresta D´oeste",
"state": {
"id": 11,
"name": "Rondônia",
"uf": "RO"
}
},
{
"id": 110002,
"name": "Ariquemes",
"state": {
"id": 11,
"name": "Rondônia",
"uf": "RO"
}
},
...
]
However the Query executed by findAll makes a SELECT in the City table and for each City makes a Select in State. Ex: If it has 3 city it makes a select to bring the 7 cities, and for each city it makes select in State.
Query Made by findAll:
I know how to solve using by placing a findAll in my Repository and giving a @Override on it and @Query with fetch, but so I can’t use Example and Examplematcher.
Someone knows a way to solve this, but without ceasing to use Example and Examplematcher????