java代码:
public static List<Map<String, Object>> doProcedure(String sql, Object... params) {
Connection conn = null;
CallableStatement cs = null;
Map<String, Object> map = null;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
conn = getConn();//获得连接
CallableStatement stmt = conn.prepareCall("BEGIN pro_name(?, ?); END;");//调用存储过程
if (null != params && params.length > 0) {
stmt.setObject( 1, params[0]);// params存储值的顺序与 ?的顺序一样
stmt.registerOutParameter( 2,-10); /* OracleTypes.CURSOR = -10 */
}
stmt.execute();//执行
ResultSet rs = (ResultSet) stmt.getObject(2);//得到结果集
List<String> columnNames = getAllColumnNames(rs);// 获取结果中的所有列表
while (rs.next()) {
map = new HashMap<String, Object>();
for (String cn : columnNames) {// 循环列名,将列表作用map的键,根据列表获取到每个列的值
map.put(cn, rs.getObject(cn));
}
list.add(map);
}
// rs.getString("STAFFID") ;//得到某个字段的值
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(null, cs, conn);// 关闭所有连接
}
return list;
}
注:我用的oracle数据库
存储过程:
CREATE OR REPLACE PROCEDURE pro_name (
stid IN VARCHAR2,
ref_cursor OUT sys_refcursor /* 这个sys_refcursor类型在SYS.STANDARD包中 */
)
AS
BEGIN
OPEN ref_cursor FOR
SELECT *
FROM table_naem
END;
鉴借:http://blog.sina.com.cn/s/blog_7ffb8dd501013diw.html
http://blog.csdn.net/u012975700/article/details/51212614
mapper.xml文件配置如下:
<select id="findfilminfobytypename" statementType="CALLABLE"
parameterMap="paramMap" useCache="false">
call findfilminfobytypename(?,?) //调用
</select>
<parameterMap type="java.util.Map" id="paramMap">
<parameter property="tn" mode="IN" jdbcType="varchar" /> //变量名 入参 参数类型
<parameter property="num" mode="OUT" jdbcType="integer" />//变量名 出参 参数类型
</parameterMap>
注:我用的oracle数据库
存储过程:
create procedure findfilminfobytypename(typename varchar(100) , out num int)
begin
select count(*) into num
from filminfo
inner join filmtype
on filmtype.typeid=filminfo.typeid
where typename=tn;
end
代码调用:
//测试存储过程 这里用了junit4
public void TestPro() throws IOException{
Map<String , Object> params =new HashMap<String,Object>();
params.put("tn", "战争");
params.put("num", new Integer(0));
SqlSession session=MybatisHelper.getSession();
session.selectOne("com.yc.mapper.FilmMapper.findfilminfobytypename", params);
System.out.println(params.get("num"));
}
大概过程是这样,我的部分代码已封装,若有什么问题,请留言.
共勉!!