服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|

服务器之家 - 编程语言 - JAVA教程 - 详解java调用存储过程并封装成map

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

2020-12-28 09:25wjch_111 JAVA教程

这篇文章主要介绍了详解java调用存储过程并封装成map的相关资料,希望通过本文能帮助到大家实现这样的功能,需要的朋友可以参考下

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

           本文代码中注释写的比较清楚不在单独说明,希望能帮助到大家,

实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
       }

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://wjch-111.iteye.com/blog/2332043

延伸 · 阅读

精彩推荐