Hibernate标准 - 排序依据

时间:2010-11-10 12:22:39

标签: java hibernate criteria

我目前有以下标准: -

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(“distance”,“function”)

理想情况下,我想对Latmin和Latmax进行限制,因为这会降低结果集,从而降低计算次数(sql也会进行两次相同的计算:S),但是任何建议都会受到最高的评价。

干杯, 罗布

1 个答案:

答案 0 :(得分: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);
}