输入参数和输出参数

输入参数parameterType

简单类型

${}#{}比较

#{任意值}或者${value}(标识符只能是value)

#{}会自动给String加上’’(自动类型转换)

${}会原样输出,但是适合于动态排序(动态字段)

#{}可以防止sql注入

${}不可以

${}#{}相同之处

都可以获取对象的值,(嵌套类型对象)

对象类型

#{属性名}或者${属性名}(对象的属性名例如stuNo)

1
2
3
4
<select id="queryStudentByAddress" resultType="top.eshyee.entity.Student" parameterType="address">
select stuno,stuname,stuage from student
where homeaddress=#{homeAddress} or schooladdress='${schoolAddress}'
</select>

嵌套类型输入参数为级联属性

1
2
3
4
5
6
7
<select id="queryStudentByAddress" resultType="top.eshyee.entity.Student" parameterType="Student">
select stuno,stuname,stuage from student where homeaddress=#{address.homeAddress} or schooladdress='${address.schoolAddress}'
</select>
<select id="queryStudentBystuNameOrAge" resultType="top.eshyee.entity.Student" parameterType="Student">
select stuno,stuname,stuage from student
where stuname like '%${stuName}%' or stuage=#{stuAge}
</select>

传入为hashmap

1
2
3
4
<select id="queryStudentBystuNameOrAgewithHashmap" resultType="top.eshyee.entity.Student" parameterType="HashMap">
select stuno,stuname,stuage from student
where stuname like '%${stuName}%' or stuage=#{stuAge}
</select>

调用存储过程

存储过程的传入参数在mybatis中用map来传递(Hashmap)
CALLABLE设置sql 的调用方式是存储过程
输出参数通过map的get方法获取

查询某个年级的所有学生总数

数据库里
1
2
3
4
5
6
create or replace procedure queryCountByGradeWithProcadure(gName in varchar,scount out number )
as
begin
select count(1) into scount from student where graname=gname;
end;
/
mapper中
1
2
3
4
5
<select id="queryCountByGradeWithPrecadure" statementType="CALLABLE" parameterType="HashMap">
{CALL queryCountByGradeWithProcadure(
#{gName,jdbcType=VARCHAR,mode=IN},
#{sCount,jdbcType=INTEGER,mode=OUT} )}
</select>

根据学号删除学生

数据库里
1
2
3
4
5
6
create or replace procedure deleteStuBystunoWithProcedure(sno in number)
as
begin
delete from student where stuno=sno;
end;
/
mapper中
1
2
3
<delete id="deletestuByStunoWithPrecadure" statementType="CALLABLE" parameterType="HashMap">
{CALL deleteStuBystunoWithProcedure(#{sno,jdbcType=INTEGER,mode=IN})}
</delete>

输出参数

resultType

简单类型,实体对象类型,实体对象类型的集合之前有提到过,此处不再赘述。

输出为HashMap

通过别名作为map的key

1
2
3
<select id="queryStudentWithHash" resultType="HashMap">
select stuno "no",stuname "name" from student
</select>

resultMap

解决实体类型属性与数据表字段名不一致(前面有用到)

也可以使用HashMap+resultType