Hibernate - getHibernateTemplate在查询中重复参数

时间:2015-04-23 06:46:06

标签: java mysql spring hibernate java-ee

String query = "SELECT Vehicle, ( 3959 * acos( cos( radians(37) ) * cos( radians( Vehicle.lat ) ) * cos( radians( Vehicle.lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( Vehicle.lat ) ) ) ) AS distance FROM VehicleDetails Vehicle";

Object[] params  = {lat,lng};

List<VehicleDetails> vehicledata = getHibernateTemplate().find(query,params);

两个参数'lat'和'lng'。查询中的数字“37”是“lat”值。该值在查询中重复两次。参数使用'?'分配但在这种情况下第一个'?'将是'lat'和2nd'?'将是'lng'并且还有另一个第3号码。如何在查询中分配'lat'参数两次?

1 个答案:

答案 0 :(得分:1)

就像这样:

String query = "SELECT Vehicle, ( 3959 * acos( cos( radians(37) ) * cos( radians( ? ) ) * cos( radians( ? ) - radians(-122) ) + sin( radians(37) ) * sin( radians( ? ) ) ) ) AS distance FROM VehicleDetails Vehicle";

Object[] params  = {lat,lng, lat};

List<VehicleDetails> vehicledata = getHibernateTemplate().find(query,params);

或使用namedParameters

 String query = "SELECT Vehicle, ( 3959 * acos( cos( radians(37) ) * cos( radians( :lat ) ) * cos( radians( :lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( :lat ) ) ) ) AS distance FROM VehicleDetails Vehicle";

 List<VehicleDetails> vehicledata = getHibernateTemplate().findByNamedParam(query,{'lat','lng'},{lat, lng});

带限制的版本:

Query q = getHibernateTemplate().getSession().createQuery(query );
q.setFirstResult(0); // modify this to adjust paging
q.setMaxResults(20);

// For named parameters
q.setParamter("lat",lat);
q.setParamter("lng",lng);

// For non named parameters
q.setParamter(0,lat);
q.setParamter(1,lng);
q.setParamter(2,lat);
List<VehicleDetails> vehicledata = q.list();