---
title: "Spring JDBC调用存储过程的几种情况"
author: "godandghost"
date: "2013-05-23T17:00:47Z"
tags: ["JDBC", "Java", "Oracle", "Spring"]
categories: ["编程语言"]
slug: "spring-jdbc"
draft: false
lastmod: "2013-06-21T10:24:32Z"
id: 1874197
url: "https://godandghost.iteye.com/blog/1874197"
---

注入spring jdbc，参见：http://godandghost.iteye.com/admin/blogs/1724763 1. 存储过程中各个出入参都是基本类型时： \[code="sql"] PROCEDURE p\_get\_province ( iv\_code VARCHAR2, --字符串类型 in\_staff\_role NUMBER, --数字类型 in\_provincial\_id NUMBER, iv\_m\_id VARCHAR2, ocur\_exec\_status OUT pkg\_ref\_cursor.gcur\_record\_set, --游标类型 ocur\_province OUT pkg\_ref\_cursor.gcur\_record\_set --游标类型 ); \[/code] \[code="java"] public static List getProvice(final Map paramMap) throws Exception { try { List list = template.execute(new ConnectionCallback() { @Override public List doInConnection(Connection conn) throws SQLException, DataAccessException { CallableStatement call = conn.prepareCall("call p\_get\_province(?,?,?,?,?,?)"); call.setString("iv\_code", paramMap.get("Report\_Id")); if (StringUtils.isNotBlank(paramMap.get("Role"))) { call.setInt("in\_staff\_role", Integer.parseInt(paramMap.get("Role"))); } else { call.setString("in\_staff\_role", null); } if (StringUtils.isNotBlank(paramMap.get("ProvinceId"))) { call.setInt("in\_provincial\_id", Integer.parseInt(paramMap.get("ProvinceId"))); } else { call.setString("in\_provincial\_id", null); } call.setString("iv\_m\_id", paramMap.get("mId")); call.registerOutParameter("ocur\_exec\_status", OracleTypes.CURSOR); call.registerOutParameter("ocur\_province", OracleTypes.CURSOR); DataSourceUtils.applyTimeout(call, template.getDataSource(), 30);// 30秒超时 call.execute(); ResultSet rs = (ResultSet) call.getObject("ocur\_exec\_status"); int status = 0; String info = ""; while (rs.next()) { status = rs.getInt("Exec\_Status"); info = rs.getString("Exec\_info"); } rs.close(); if (status == 0) { List provinceList = new ArrayList(); ResultSet rs1 = (ResultSet) call.getObject("ocur\_province"); while (rs1.next()) { MyObject mo = new MyObject(); mo.setValue(rs1.getString("province\_value")); mo.setText(rs1.getString("province")); provinceList.add(mo); } rs1.close(); return provinceList; } else { return null; } } }); return list; } catch (DataAccessException e) { throw e; } catch (Exception e) { throw e; } } \[/code] 2.存储过程中有自定义struct时 Struct类型声明： \[code="sql"] CREATE OR REPLACE TYPE header\_struct as object ( w\_id varchar2(8), a\_time date, b\_time date, token varchar2(20) ) create or replace type Report\_List as varray(2000) of REPORT\_STRUCT create or replace type REPORT\_STRUCT as object( REQUEST\_ID NUMBER(10), STATUS NUMBER(3), FILENAME VARCHAR2(200), DESCRIPTION VARCHAR2(201), REQUESTDATETIME DATE ) CREATE OR REPLACE TYPE ERROR\_MESSAGE\_STRUCT as object ( error\_type number(3), error\_code number(10), message varchar2(255) ) \[/code] 存储过程声明： \[code="sql"] CREATE OR REPLACE PROCEDURE get\_report\_list ( iv\_header IN header\_struct, iv\_function\_name IN VARCHAR2, iv\_report\_date IN DATE, ov\_report\_list OUT report\_list, ov\_error\_message OUT error\_message\_struct ) \[/code] Java代码写法： \[code="java"] public static Object\[] getReportResultList(final Header header, final String functionName, final Date dateTime) { try { return template.execute(new ConnectionCallback() { @Override public Object\[] doInConnection(Connection conn) throws SQLException, DataAccessException { Connection con = conn.getMetaData().getConnection();// 此处需要将connection类型转换一下 OracleCallableStatement call = (OracleCallableStatement) con .prepareCall("call get\_report\_list(?,?,?,?,?)"); // 存储过程第一个参数 oracle.sql.STRUCT headerStruct = getHeaderStruct(header, con); // 声明存储过程的入参 call.setSTRUCT(1, headerStruct);// 参数类型是Struct call.setString(2, functionName);// 参数类型是String call.setDate(3, dateTime); // 声明存储过程的出参 call.registerOutParameter(4, OracleTypes.ARRAY, "REPORT\_LIST");// REPORT\_LIST必须大写 call.registerOutParameter(5, OracleTypes.STRUCT, "ERROR\_MESSAGE\_STRUCT");// ERROR\_MESSAGE\_STRUCT必须大写 DataSourceUtils.applyTimeout(call, sbcTemplate.getDataSource(), 30); call.execute(); // 出参第一个结构体是一个Struct的Array oracle.sql.ARRAY array = call.getARRAY(4); List resultList = new ArrayList(); if (array != null) { Datum\[] data = array.getOracleArray(); for (Datum datum : data) { STRUCT struct = (STRUCT) datum; Datum\[] datas = struct.getOracleAttributes(); int requestId = 0; int status = 0; String fileName = ""; String description = ""; NUMBER requestIdNum = (NUMBER) datas\[0]; if (requestIdNum != null) { requestId = requestIdNum.bigIntegerValue().intValue(); } NUMBER statusNum = (NUMBER) datas\[1]; if (statusNum != null) { status = statusNum.bigIntegerValue().intValue(); } try { if (datas\[2] != null) { fileName = new String(datas\[2].getBytes(), "GBK"); } if (datas\[3] != null) { description = new String(datas\[3].getBytes(), "GBK"); } } catch (UnsupportedEncodingException e) { logger.warn("不支持的字符编码", e); } oracle.sql.DATE requestDate = (oracle.sql.DATE) datas\[4]; java.sql.Timestamp date = null; if (requestDate != null) { date = requestDate.timestampValue(); } ReportResult rr = new ReportResult(requestId, status, fileName, description, date); resultList.add(rr); } } else { System.out.println("空")； } // 第二个结构体errormessage STRUCT errorMsgStruct = call.getSTRUCT(5); ErrorMessage em = new ErrorMessage(); if (errorMsgStruct != null) { em = initErrorMessage(errorMsgStruct); } con.close(); return new Object\[] { resultList, em }; } }); } catch (Exception e) { throw e; } } private static STRUCT getHeaderStruct(Header header, Connection con) throws SQLException { java.sql.Timestamp aTime = null; java.sql.Timestamp bTime = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { java.util.Date aTimeUtil = sdf.parse(header.getaTime()); aTime = new java.sql.Timestamp(aTimeUtil.getTime()); } catch (ParseException e) { logger.note("aTime时间转换发生错误", e); } try { java.util.Date bTimeUtil = sdf.parse(header.getbTime()); bTime = new java.sql.Timestamp(bTimeUtil.getTime()); } catch (ParseException e) { logger.note("bTime时间转换发生错误", e); } Object\[] head = { header.getWitnessID(), bTime, aTime, header.getToken() }; oracle.sql.StructDescriptor headerDesc = oracle.sql.StructDescriptor.createDescriptor("HEADER\_STRUCT", con);// HEADER\_STRUCT必须大写 oracle.sql.STRUCT headerStruct = new oracle.sql.STRUCT(headerDesc, con, head); return headerStruct; } private static ErrorMessage initErrorMessage(STRUCT errorMsgStruct) { try { Datum\[] datas = errorMsgStruct.getOracleAttributes(); int errorType = 0; int errorCode = 0; String errorMsg = ""; NUMBER errorTypeNum = (NUMBER) datas\[0]; if (errorTypeNum != null) { errorType = errorTypeNum.bigIntegerValue().intValue(); } NUMBER errorCodeNum = (NUMBER) datas\[1]; if (errorCodeNum != null) { errorCode = errorCodeNum.bigIntegerValue().intValue(); } try { if (datas\[2] != null) { errorMsg = new String(datas\[2].getBytes(), "GBK"); } } catch (UnsupportedEncodingException e) { logger.warn("不支持的字符编码", e); } ErrorMessage em = new ErrorMessage(errorCode, errorType, errorMsg); return em; } catch (SQLException e) { return null; } } \[/code] 需要注意的是，oracle的驱动包与字符集包必须对应，否则一旦Struct结构体中有字符串（无论是不是中文）都是乱码，导致Struct结构体初始化失败。我用的oracle驱动包是ojdbc6.jar，就必须用与其对应的orai18n.jar。关于乱码问题可以参见：http://blog.csdn.net/hzw2312/article/details/8444462 另注： 当使用Connection con = conn.getMetaData().getConnection();转换数据库连接时，此连接相当于新建了一个连接，不受Spring JDBC控制，不会自动回收。所以在程序最后需要手动关闭:con.close();