因此,我已经看到所有线程在类似主题上的堆栈溢出,但是我没有找到解决问题的方法。
我正在尝试创建一个Criteria查询,并得到以下SQL(简化的第一个SQL):
SELECT latitude FROM stations WHERE (ABS(latitude - 45.893227) <= 0.2)
Run Code Online (Sandbox Code Playgroud)
但这给了我这个错误:
java.sql.SQLDataException: The resulting value is outside the range for the data type DECIMAL/NUMERIC(31,31).
Run Code Online (Sandbox Code Playgroud)
那是因为我的纬度是varchar(25)类型。因此,可以解决此问题(第二条SQL):
SELECT latitude FROM stations WHERE (ABS(CAST(latitude AS DECIMAL) - 45.893227) <= 0.2)
Run Code Online (Sandbox Code Playgroud)
但是现在我需要使用Criteria语法。这是我的方法:
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);
//this <Float> cast actually does nothing:
Expression<Float> Lat = stations.get("latitude");
Expression<Float> Lon = stations.get("longitude");
//make a list of conditions
List<Predicate> predicates = new ArrayList<>();
for (Address a : addresses) {
Float aLat = Float.valueOf(a.getLatitude());
Float aLon = Float.valueOf(a.getLongitude());
//condition: |station.Lat - address.Lat| <= distance
//le() = lessThan, abs() = absolute, diff() = subtraction
Predicate condLat = cb.le(cb.abs(cb.diff(Lat, aLat)), distance);
Predicate condLon = cb.le(cb.abs(cb.diff(Lon, aLon)), distance);
//if I do: Lat.as(Float.class) it won't cast on runtime!
predicates.add(condLat);
predicates.add(condLon);
}
//add the array of conditions to the WHERE expression, connected with AND:
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
TypedQuery<Stations> q = em.createQuery(cq);
return q.getResultList();
}
Run Code Online (Sandbox Code Playgroud)
有了这些代码,我得到了第一个SQL,而我想要了第二个SQL,只是无法获得运行时强制转换功能。我尝试过的Criteria类型转换函数在运行时不起作用。我该如何解决这个问题?
经过一番搜索后,我找到了一种使用 java derby DOUBLE 函数通过 CriteriaBuilder 函数强制运行时强制转换的方法:
Expression Lat = stations.get("latitude");
Expression LatCast = cb.function("DOUBLE", Float.class, Lat);
Run Code Online (Sandbox Code Playgroud)
我得到这个 SQL 查询转换:
DOUBLE(LATITUDE)
Run Code Online (Sandbox Code Playgroud)
参考文献:http://www.javadb.net/double-function.html,http : //www.objectdb.com/api/java/jpa/criteria/CriteriaBuilder/function_String_Class__Expression__
它适用于大多数受支持的数据库功能。
| 归档时间: |
|
| 查看次数: |
2445 次 |
| 最近记录: |