![](/img/trans.png)
[英]Hibernate Query, how to use like or = on where clause depend on value passed
[英]how to use like clause in mysql for variable of double type using hibernate
我有下表所示。 like子句不適用於hibernate和mysql中的double型變量。 like子句將如何工作一倍,或者如何解決該問題。 我沒有例外,只是返回的obj為null。
表:-
CREATE TABLE `loc_location` (
`location_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A-Approved\nD-Drafted\nP-Pending\nR-Reject\nS-Scheduled',
PRIMARY KEY (`location_id`),
UNIQUE KEY `location_id_UNIQUE` (`location_id`),
UNIQUE KEY `latitude_UNIQUE` (`latitude`),
UNIQUE KEY `longitude_UNIQUE` (`longitude`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
表值:-
location_id latitude longitude creation_date status
1 19.175934 72.8622649 2015-08-22 14:09:31 A
2 19.177283 72.8636139 2015-08-22 14:09:31 A
3 19.174585 72.8609159 2015-08-22 14:09:31 A
查詢:-經度= 72.862,緯度= 19.175
select this_.location_id as location1_16_0_, this_.creation_date as creation2_16_0_, this_.latitude as latitude3_16_0_, this_.longitude as longitud4_16_0_, this_.status as status5_16_0_ from loc_location this_ where this_.longitude like ? and this_.latitude like ?
休眠方式:
public <T extends Serializable> T getEntityWithLikeClause(T x, Map<String, Object> ceriteriaMap, Session session) throws PersistenceException{
T obj=null;
Criteria criteria = null;
try {
criteria= session.createCriteria(x.getClass());
if(ceriteriaMap!=null && criteria !=null){
Set<String> set=ceriteriaMap.keySet();
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
String ceriteria = iterator.next();
Object value = ceriteriaMap.get(ceriteria);
criteria.add(Restrictions.like(ceriteria, value));
}
}
obj = (T) criteria.uniqueResult();
}catch (Exception e) {
throw new PersistenceException(e);
}
return obj;
}
其中ceriteriaMap如下,經度1 = 72.862,緯度1 = 19.175:
Map<String, Object> ceriteriaMap = new HashMap<String, Object>();
ceriteriaMap.put("lat", latitude1);
ceriteriaMap.put("lng", longitude1);
Restrictions.ilike
不能用於數字字段。
默認語法:
Restrictions.ilike(fieldName, SearchTerm, MatchMode.ANYWHERE (Optional) )
| | |
String String MatchMode (optional argument)
因此,您將無法將數字值傳遞給String參數。 即使將其作為String.valueOf(numbercValue)
傳遞,您也會遇到異常,因為hibernate會嘗試根據hbm或注釋配置將其轉換為數字數據類型
我用下面的代碼混合like
與標准。
critria.add(
Restrictions.sqlRestriction(" column_name LIKE '%"+SearchTerm+"%' "))
| |
Column Name (Not fieldName) Search Term prefixed and Suffixed with % as per needs
您不能對非varchar(string)類型使用LIKE。 它僅適用於字符串模式。 在任何數字情況下,您都必須使用gt / lt邏輯或將字段更改為varchar並將此字段解析為通過行映射器加倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.