MyBatis (四) 注解和存储过程

1. sql 公共片段

"publicfindemp">
        select e.*,depname from employee e ,department d
        where d.depid=e.depid

使用 sql 公共片段:

 <include refid="publicfindemp"/>
 
    <select id="findEmloyee" parameterType="PageUtil" resultMap="empMap">
        <choose>
            
            <when test="startrow!=0 and pagesize>0" >
                <include refid="publicfindemp"/>
                limit #{startrow},#{pagesize}
            when>
            
            <otherwise>
                <include refid="publicfindemp"/>
            otherwise>
        choose>
    select>

2. 存储过程原理

delimiter //
create procedure pro_emp(in startrow int,in pagesize int)
begin
   select e.*,d.depname from employee e,department d
    where d.depid=e.depid limit startrow,pagesize;
end 
//
delimiter;
delimiter //
create procedure proc_emptotalcount(out empcount int)
begin
    select count(*) into empcount from employee e,department d
    where d.depid = e.depid;
end
//
delimiter;

在 mapper.xml 里面这么写:
1)IN

<select id="findByPrimaryKey" 
parameterMap="paramMap" >>>>注意要写parameterMap
statementType="CALLABLE" >>>>表示是存储过程
resultType="com.pojo.Employee">
        CALL EmployeeSys.proc_empbyid(?)
select>
"paramMap" type="Employee">
  property="empId" mode="IN" jdbcType="INTEGER"/>
 

type:封装 java 对象的类型
jdbcType:参数的数据类型,必须是引用数据类型,必须是大写;
mode:存储过程的参数的类型,如果是输入参数则是IN,输出参数则是OUT;
2)OUT

 <select id="getTotalcount" 
 parameterMap="totalcountMap" 
 statementType="CALLABLE">
      CALL EmployeeSys.proc_emptotalcount(?)
  select>

<parameterMap id="totalcountMap" type="PageUtil">
     <parameter property="totalcount" mode="OUT" jdbcType="INTEGER"/>
parameterMap>

3)关于 out 的 测试

        System.out.println("---getTotalcount(PageUtil pageUtil)---");
        PageUtil pageUtil1 = new PageUtil(1,2);
        mapper.getTotalcount(pageUtil1);
        System.out.println(pageUtil1.getTotalcount());

理解:存储过程 out 的是:out 出property=”totalcount”,并且是封装在type=”PageUtil”里面的,所以用pageUtil1.getTotalcount() 来接。select count(*) into empcount ,方法不需要返回值,直接进属性里面捞。

3)注解

在 mapper接口里面直接写sql 语句,就不需要使用 xml 文件了:

 @Select("select * from project")
 List<Workorder> findName();
 // 分页查询
 @Select("select w.*,p.projectname from Workorder w,project p where   p.id=w.projectid limit #{startrow},#{pagesize}")
 List<Workorder> findPage(PageUtil pageUtil);

你可能感兴趣的:(mybatis,存储过程)