如何在hibernate中编写sql内部查询?

时间:2014-08-26 10:27:40

标签: java sql hibernate arraylist

目前我的方法使用基本的jdbc概念,

public static ArrayList<VehicleDetailsBean>
   getAllVehicleDetails(String groupId,String clientId) 
                 throws ClassNotFoundException, SQLException {

ArrayList<VehicleDetailsBean> vehicleDetailsList =
   new ArrayList<VehicleDetailsBean>(); 
try {
        Statement statement = connection.createStatement();
        String  sql ="SELECT a.vehicleno,a.lat,a.lng,a.status, "+
        "a.rdate,a.rtime from latlng a,vehicle_details b where"+ 
        "a.vehicleno=b.vehicleno and b.clientid='"+
        clientId+"'  and b.groupid in(select groupid from group_details"+
        " where groupname='"+groupId+"' and clientid='"+clientId+"')";

        ResultSet rs = statement.executeQuery(sql);

        while(rs.next()) {  
            VehicleDetailsBean vehicleDetailsBean=new VehicleDetailsBean();
            vehicleDetailsBean.setVehicleno(rs.getString("vehicleno"));
            vehicleDetailsBean.setLat(rs.getString("lat"));
            vehicleDetailsBean.setLng(rs.getString("lng"));
            vehicleDetailsBean.setStatus(rs.getString("status"));
            vehicleDetailsBean.setRdate(rs.getInt("rdate"));
            vehicleDetailsBean.setRtime(rs.getString("rtime"));
            vehicleDetailsList.add(vehicleDetailsBean);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

它返回ArrayList。现在我想把它改成休眠所以我将上面的代码更改为,

  query = session.createQuery(hqlquery);//I am not getting how to write hqlquery
    List<Object[]> groupList = query.list();
    for(Object[] arr : groupList){
        System.out.println(Arrays.toString(arr));
    }

这样做会返回List个对象,但我的方法必须返回ArrayList。所以任何人都可以帮我编写查询并将结果返回为ArrayList

2 个答案:

答案 0 :(得分:0)

如果要将其作为ArrayList返回,则可以使用ArrayList添加它。

List<VehicleDetailsBean> groupList = (List<VehicleDetailsBean>) query.list();
vehicleDetailsList.addAll(groupList);
return vehicleDetailsList;

您可以看到类似的问题herea way to cast here

修改

或尝试添加entity

List<LatitudeBean> bean = (List<LatitudeBean>) session.createSQLQuery(query)
.addEntity(LatitudeBean.class).list();
//add to ArrayList here

答案 1 :(得分:0)

你可以用丑陋的方式做到:

query = session.createQuery(hqlquery); // Take a walk in Hibernate Docs for HQL Queries
List<?> groupList = query.list();
ArrayList<VehicleDetailsBean> result = new ArrayList<VehicleDetailsBean>(groupList.size());
for (Object o : groupList) {
  result.add((VehicleDetailsBean) o);
}
return result;