mybatis学习之mybatis中mapper中传入的参数处理

来源:互联网 发布:带虚化的拍照软件 编辑:程序博客网 时间:2024/05/18 02:16

单个参数时,mybatis不做任何处理
例如:

<select id="getPersonByid" resultType="mybatis_01.Person">        select * from person where id=#{id}</select>此时由于只有一个参数,无论#{}中写什么,都是可以的

多个参数时,mybatis会做特殊的参数处理,以map的形式将参数封装起来,例如

<select id="getPersonByidAndName" resultType="mybatis_01.Person">        select * from person where id=#{id} and name=#{name}</select>

由于mybatis多个参数时会以parameter1……parameterN的形式或者按照索引从0……N-1的形式表示,此时会出现错误,必须按照以下方法来写

<select id="getPersonByidAndName" resultType="mybatis_01.Person">        select * from person where id=#{parameter1} and name=#{parameter2}</select>或者<select id="getPersonByidAndName" resultType="mybatis_01.Person">        select * from person where id=#{0} and name=#{1}</select>

由于这样的处理方式会很多不便,看起来不是很直观,因此需要为参数命名,使用以下的方法@para(参数名)

public Person getPersonByidAndName(@Param("id")Integer id,@Param("name")String name);

此时以下方法就可以使用了

<select id="getPersonByidAndName" resultType="mybatis_01.Person">        select * from person where id=#{id} and name=#{name}</select>

在多个参数时,若传入的参数是已经定义的实体类的属性,为了方便,可以通过直接传入实体类的形式来完成查询,例如

public Person getPersonByidAndName(Person person);<select id="getPersonByidAndName" resultType="mybatis_01.Person">        select * from person where id=#{id} and name=#{name}</select>

若传入的参数不是已经定义好的实体类的属性,且该查询方法不会经常被调用,为了方便,可以通过将要传入的参数封装成map的形式,在查询时直接传入map进行查询,如果传入的参数不是已经定义好的实体类且该方法要经常调用,那么可以自己手写一个TO(数据传入类),方便查询。

特别注意一点,之前说过了当传入一个参数时不做任何处理,但当传入的参数类型为Collection类型时(List,Set),mybatis也会将参数封装成map,此时map的key为类型的小写 即 List类型的key为list。
例如

public Person getPersonByid(List<Integer> ids);<select id="getPersonByid" resultType="mybatis_01.Person">        select * from person where id=#{list[0]}</select>
原创粉丝点击