2010-11-10 91 views
1

我目前有以下標準: -Hibernate的標準 - 順序按

Criteria addr = criteria.createCriteria("location.address"); 
       addr.add((Restrictions.and(Restrictions.between("latitude", latmin,  
         latmax), Restrictions.between("longitude", truelongmin, truelongmax)))); 

       String sql = "SQRT(POW(69.1 * ({alias}.latitude - " + point[1]  
         +") , 2) + POW(69.1 * ("+point[0] +" - {alias}.longitude) * COS({alias}.latitude /" 
         +" 57.3) , 2)) < "+distance;  
       addr.add(Restrictions.sqlRestriction(sql)); 

我想最好做的是能夠通過距離來訂購。 MySQL的等價物是: -

SELECT * , (
SQRT(POW(69.1 * (latitude - 51.3814282) , 2) + POW(69.1 * (- 2.3574537 - longitude) * COS(latitude/57.3) , 2)) 
) AS distance 
FROM `address` 
WHERE (
SQRT(POW(69.1 * (latitude - 51.3814282) , 2) + POW(69.1 * (- 2.3574537 - longitude) * COS(latitude/57.3) , 2)) 
) < 10.0 
ORDER BY distance DESC 
LIMIT 0 , 30 

什麼是在Hibernate中做到這一點的最佳方法?我試過createCriteria/createAlias(「距離」,「功能」)

理想情況下,我想這樣做後張對Latmin和Latmax的限制,因爲這降低了結果集,從而計算的數量(也是SQL相同的計算兩次:S),但任何建議將不勝感激。

乾杯, 羅布

回答

2

Hibernate支持原生查詢只是這樣:)情況

編輯**

我沒有測試過,但是像下面應該工作:

StringBuilder sql = new StringBuilder(); 

sql.append("SELECT *"); 
sql.append(", (SQRT(POW(69.1 * (latitude - 51.3814282) , 2) + POW(69.1 * (- 2.3574537 - longitude) * COS(latitude/57.3) , 2))) AS distance"); 
sql.append(" FROM `address`"); 
sql.append(" WHERE (SQRT(POW(69.1 * (latitude - 51.3814282) , 2) + POW(69.1 * (- 2.3574537 - longitude) * COS(latitude/57.3) , 2))) < 10.0"); 
sql.append(" ORDER BY distance DESC"); 
sql.append(" LIMIT 0 , 30"); 

SQLQuery query = session.createSQLQuery(sql.toString()); 
// call query.addScalar(..) for other fields you select 
query.addScalar("distance", Hibernate.BIG_DECIMAL) 

//Where AddressBean is the object that maps to a row of this resultset 
query.setResultTransformer(Transformers.aliasToBean(AddressBean.class)); 

List<AddressBean> list = new ArrayList<AddressBean>(100); 
for (Object object : query.list()) { 
    list.add((AddressBean)object); 
}