日期:2014-05-16  浏览次数:20408 次

Hibernate 中执行JDBC

Hql ="SELECT l.fgid,l.fgname,l.icon,l.fglev,l.fginstruction,l.reply_count,l.typeid,g.ucounts FROM AppGameList as l left join on(select fgid,count(fgid) As ucounts from AppWaJin GROUP by fgid) as g On g.fgid=l.fgid ORDER BY ucounts DESC limit 21"

函数:
public List<Map<String,String>> test(final String sql) {
            return (List<Map<String, String>>) getHibernateTemplate().execute(new HibernateCallback() {
              public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Connection conn = null;
                PreparedStatement pstmt =null;
                ResultSet rs=null;
                Transaction transaction = null;
                List<Map<String,String>> rows =null;
                try{
                    transaction = session.beginTransaction();
                    conn = session.connection();
                    pstmt = conn.prepareStatement(sql);
                    rs =pstmt.executeQuery();
                    rows= new ArrayList<Map<String,String>>();
                    ResultSetMetaData rsmd=rs.getMetaData();
                    int columnCount=rsmd.getColumnCount();
                    String []columns=new String[columnCount];
                    for(int i=1;i<=columnCount;i++){
                        columns[i-1]=rsmd.getColumnLabel(i);
                    }
                    rsmd=null;
                    Map<String,String> row=null;
                    while (rs.next()){
                        row=new HashMap<String,String>(columnCount);
                        for (int i=1;i<=columnCount;i++) {
                            row.put(columns[i-1],rs.getString(i));
                        }
                        rows.add(row);               
                    }
                    row=null;
                    columns=null;
                    transaction.commit();
                }catch(Exception exception){
                    exception.printStackTrace();
                    if(transaction!=null){
                        transaction.rollback();
                    }
                }finally {
                    try {
                        if(transaction!=null){
                            transaction=null;
                        }
                        if(rs!=null){
                            rs.close();
                            rs=null;
                        }
                        if(pstmt!=null){
                            pstmt.close();
                            pstmt=null;
                        }
                        if(conn!=null){
                            conn.close();
                            conn=null;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                return rows;
            }
            });
          }