mybatis参数传递

patameterType属性

  • 属性作用:在XXXMapper.xml中等标签的parameterType可以控制参数类型,参数由外面提供;
<!-- 
java方法中:public void selById(int id)
People p = session.selectOne("a.b.selById",1)
					1为传进a.b.selById的参数
-->

<select id="selById" resultType="xxx.xxx.xxx.People" parameterType="int">
       select * from people where id=#{0}
       <!-- #{0}代表:selById(int id)的第一个参数,下标从0开始 -->
</select>
  • SQLSession的selectList()和selectOne()的第二个参数和selectMap()的第三个参数都表示方法的参数。

获取参数:

在Mapper.xml中通过#{0}获取参数:
	①使用索引,从0开始,第一个参数;
	②也可以使用#{param1},第一个参数,param为固定字符串,不可以变更。
	③如果只有一个参数,mybatis对#{基本数据类型或String}里面的内容没有要求,只要写内容即可,内容随便;
	④如果参数是对象#{属性名};
	⑤如果参数是map写成#{key};
	
  • 注:Map或对象可以传多个参数;

参数为普通类型时,用#

<select id="selById" resultType="com.czxy.pojo.People" parameterType="int">
       select * from people where id=#{0}
</select>

参数为对象类型时,用$

<select id="selById" resultType="xxx.xxx.xxxPeople" parameterType="xxx.xxx.xxx.People">
       select * from people where id=${属性名}
</select>

前提:该属性必须有get和set方法

参数为map时,用#

map.put("id","1");
map.put("name","zhangsan");
<select id="selById" resultType="xxx.xxx.xxxPeople" parameterType="map">
       select * from people where id=#{id} and name=#{name}
</select>

参数获取方式#{} 和 ${}的区别

  • #{}获取参数的内容支持索引获取,param1获取指定位置的参数,并且sql使用?占位符,是将#{}获取到的内容填入?占位符位置,生成查询语句;
<select id="selById" resultType="People" parameterType="int">
       select * from people where id=#{0}
</select>

语句: select * from people where id=?,将参数填入?。就是prepareStatement();语句执行。
  • ${}是使用字符串拼接,不使用?占位符,传入参数为对象类型,默认找${参数的get或set方法},查询时将${}中的内容拼接到查询语句后。
<select id="selById" resultType="People" parameterType="xxx.xxx.xxx.People">
       select * from people where id=${id}
</select>

语句: select * from people where id=People.getId();

如果是:select * from people where id=${0}
语句: select * from people where id=0;
  • 基本用#{}

xml文件转义标签

  • 如果在xml文件中出现“<”、“>”,双引号 等特殊字符时可以使用XML文件转义标签(XML自身的)
  • <![CDATA[内容]]>
<select id="test" resultType="xxx.xxx.xxx.People" parameterType="int">
       <![CDATA[ select * from people where id < #{0} ]]>
</select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值