欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java调用存储过程并封装成map

程序员文章站 2022-06-07 11:30:27
...
public List<Map<String , Object>> doCallProcedure(String procedureString,String[] parameters)
                                     throws PersistentDataOperationException {
                         if (!isReady ()) {
                                     throw new PersistentDataOperationException( "DAO is not ready.");
                         }
                        ResultSet rs = null;
                        List<Map< String, Object>> list = new ArrayList<Map<String ,Object>>();
                         try {
                                     Connection con=session.connection();
                                     String procedure = "{call "+procedureString+ "(?,?,?) }"; //拼装调用存储过程字符串
                                    CallableStatement cstmt = con.prepareCall (procedure ); //调用存储过程
                                    cstmt.setString (1,parameters [0 ]); //设置入参
                                    cstmt.setInt (2, Integer. parseInt( parameters[ 1])) ;//设置入参
                                    cstmt.registerOutParameter (3, oracle.jdbc.OracleTypes.CURSOR ); //设置出参
                                    
                                    cstmt.execute (); //执行提交
                                    rs = (ResultSet ) cstmt.getObject (3 ); //获取出参,3为参数顺序数
                                    ResultSetMetaData rsm =rs.getMetaData (); //获得列集
                                    Map< String, Object> map= null;
                                     int col = rsm.getColumnCount ();   //获得列的个数
                                     String colName [] = new String[ col] ;//列名集合
                                     for (int i = 0; i < col; i++) {
                                                colName [i ] = rsm.getColumnName (i+1 );
                                     }
                                     while( rs.next()){
                                                 //注意访问结果集是从索引位置1开始的,而不是0
                                                map = new HashMap< String, Object> ();
                                                 for (int j = 0; j < colName.length; j++) {
                                                            map.put (colName [j ], rs.getString (j+1 ));
                                                 }
                                                list.add (map );
                                     }
                                     session.flush ();
                         } catch (HibernateException e) {
                                     throw new PersistentDataOperationException( e) ;
                         } catch (SQLException e) {
                                    e.printStackTrace ();
                         }
                         return list;
             }

 

相关标签: java 存储过程