oracle存储过程----mybatis传入参数调用存储过程查询

版权声明:重在参与,贵在分享 https://blog.csdn.net/wohaqiyi/article/details/82799976

  上一篇的链接是 oracle存储过程----异常的写法介绍

  有这样的需求,比如共有表B1-B17 17张表,现在要求传入年度、行政区划,查询出所有符合条件的B1-B17的所有记录,(当然,仅查询这些表中共同有的字段),因为这算是跨表查询了。
  一般我们写的sql可能如下:

select id,nd,TBRQ,tbrmc,zt,b_type from b1 where nd=#{ndreq} and xzqhdm=#{xzqhdmreq}
union all 
select id,nd,TBRQ,tbrmc,zt,b_type from b2 where nd=#{ndreq} and xzqhdm=#{xzqhdmreq}
union all 
select id,nd,TBRQ,tbrmc,zt,b_type from b3 where nd=#{ndreq} and xzqhdm=#{xzqhdmreq}
union all 
... //省略其他的

   17张表写下来,把这个sql贴到我们的Mapper.xml 里,每次调用速度势必会有影响,毕竟这么一大堆每次编译一下。可以将这段查询sql,封装成一个存储过程,每次调用存储过程,这样不仅预编译sql,而且项目里边也不会看起来太乱。具体操作如下:

1.创建存储过程 (下边这个存储过程我是在mysql里建的,并不影响)

  下边的存储过程,参数nedreqxzqhdmreq 对应的类型 ,mysql中必须要给出长度,oracle 里倒是可以不给出长度。
   另外,begin 前边,可以设置参数,如果设置参数,大家可以查,mysql 存储过程里,必须加as 的,但是,在oracle 数据库里is 也是可以的。
   最后,end 前边,在这个sql结束后必须要有; ,否则报错。
具体我写的是如下的存储过程,就是写的多而已,挺简单的查询。你们可以用select * from table where args='value1' 这样的来测试即可。

create PROCEDURE sjtb_work_procedure(ndreq int(4),xzqhdmreq varchar(50))
BEGIN
  select a.b_type,a.b_name,a.b_sort,c.nd,c.tbrq ,c.zt,c.id,c.tbrmc from sjtb_table_name  a
left join 
(select b.* from (select id,nd,TBRQ,tbrmc,zt,b_type from b1 where nd=ndreq and xzqhdm=xzqhdmreq
union all 
select id,nd,TBRQ,tbrmc,zt,b_type from b2 where nd=ndreq and xzqhdm=xzqhdmreq
union all 
.....省略其他表
select id,nd,TBRQ,tbrmc,zt,b_type from b17 where nd=ndreq and xzqhdm=xzqhdmreq
) b )c on a.b_type=c.b_type order by a.b_sort;
END
2.mybatis的xml里配置

   mybatis里的xml配置与普通的sql并没有区别,调用存储过程使用call

<resultMap id="BaseResultMap" type="znxd.tjzb.model.sjtb.SjtbWork">
    <result column="id" property="id" jdbcType="VARCHAR" />
    <result column="b_type" property="bType" jdbcType="VARCHAR" />
    <result column="b_name" property="bName" jdbcType="VARCHAR" />
    <result column="b_sort" property="bSort" jdbcType="VARCHAR" />
    <result column="nd" property="nd" jdbcType="VARCHAR" />
    <result column="tbrq" property="tbrq" jdbcType="VARCHAR" />
    <result column="tbrmc" property="tbrmc" jdbcType="VARCHAR" />
    <result column="zt" property="zt" jdbcType="VARCHAR" />
  </resultMap>
  
 <select id="selectSjtbXiangProcedure" parameterType="znxd.tjzb.model.sjtb.SjtbWork" resultMap="BaseResultMap">
 <!--用call来调用存储过程-->
    call sjtb_work_procedure(#{nd},#{xzqhdm});
  </select>

   当然这只是针对我这种传少量参数的,如果多个参数的,后边再写。

3.调用接口

  其实这一步可以不用写了,第二步都写了,后边就是mybatis 的用法了。为了更直观,连mapper.java 接口也贴出来。

public interface SjtbWorkMapper {
    List<SjtbWork> selectSjtbXiangProcedure(SjtbWork sjtbWork);
}

  后边如果再写新的,会在这里补充上地址的

猜你喜欢

转载自blog.csdn.net/wohaqiyi/article/details/82799976
今日推荐