So, I saw all the threads when the stack overflowed on similar topics, but I did not find a solution for my problem.
I try to create a Criteria query and I get this SQL (1st SQL, simplified):
SELECT latitude FROM stations WHERE (ABS(latitude - 45.893227) <= 0.2)
but he gives me this error:
java.sql.SQLDataException: The resulting value is outside the range for the data type DECIMAL/NUMERIC(31,31).
This is because my latitude is of type varchar (25). So this fixes (2nd SQL):
SELECT latitude FROM stations WHERE (ABS(CAST(latitude AS DECIMAL) - 45.893227) <= 0.2)
But now I need to do this in Criteria syntax. This is my method:
public List<Stations> searchStations(Float distance, List<Address> addresses) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Stations> cq = cb.createQuery(Stations.class);
Root<Stations> stations = cq.from(Stations.class);
Expression<Float> Lat = stations.get("latitude");
Expression<Float> Lon = stations.get("longitude");
List<Predicate> predicates = new ArrayList<>();
for (Address a : addresses) {
Float aLat = Float.valueOf(a.getLatitude());
Float aLon = Float.valueOf(a.getLongitude());
Predicate condLat = cb.le(cb.abs(cb.diff(Lat, aLat)), distance);
Predicate condLon = cb.le(cb.abs(cb.diff(Lon, aLon)), distance);
predicates.add(condLat);
predicates.add(condLon);
}
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
TypedQuery<Stations> q = em.createQuery(cq);
return q.getResultList();
}
With this code, I get the first SQL, and I want the second. I just can't get this runtime functionality. The selection functions of the Criteria type that I tried do not work at runtime. How do I solve this problem?
source
share