mybatis使用注意的细节

1.mybatis对sql执行后会对结果进行封装,如果没有返回任何记录,只是封装后的对象没有值,而对象并不为空null;

(这个问题疏忽坑了两次,在对返回数组结果进行判断的时候,我用的if(Array!=null) 结果是判断正确,应该if(Array.length!=0)做判断记录是否为空)

 

2.mapper的xml文件中,if<test="ids.length!=0  and ids!=null "> 这里的与运算是用的and

 

3.数组数据的绑定问题

在这里传进来的的参数是一个整型数组,collection中的参数就是"array",不能为其他值

 <select id="findSelectedItemsList" parameterType="Integer[]" resultType="ItemsCustom">
        select * from item
        <where>
        <!-- 传递数组 -->
        <if test="array!=null">
        <foreach collection="array" index="index" item="item" open="and id in(" separator="," close=")">
            #{item} 
        </foreach>
        </if>
        </where>
    </select>    

如果传进来的是一个pojo对象,对象中有一个数组属性ids,那么collection传进来的参数就必须是属性变量ids。

<insert id="createRelation" parameterType="com.xidian.ssm.po.Relation">
   <if test="ids.length!=0 and ids!=null">
        <foreach close="" collection="ids" index="index" item="ref_id" open="" separator=";">
             insert into relation (id,ref_id) value(#{id,jdbcType=INTEGER},#{ref_id,jdbcType=INTEGER}) 
        </foreach>
    </if>
</insert>

 

4. 参数为String时的数据绑定问题

假设有下面一Dao接口方法

public Account findByAccountType (String type)throws DaoException;

 

对应的Mapper.xml

<select id="findByAccountType " parameterType="string" resultType="account">
    select *
    form account
    <where>
        <if test ="type != null">
            type=#{type}
        </if>
    </where>
</select>

 

一般我们都是按这样的方式来写的,对于其他类型是没错的,但是如果为String的话会抛下面的异常:

There is no getter for property named 'type ' in 'class java.lang.String' 

 

因为MyBatis要求如果参数为String的话,不管接口方法的形参是什么,在Mapper.xml中引用时需要改变为_parameter才能识别 :

<select id="findByAccountType " parameterType="string" resultType="account">
    select *
    form account
    <where>
        <if test ="_parameter!= null">
            type=#{_parameter}
        </if>
    </where>
</select>

 

5.对字符串参数进行是否相等 比较时的问题

错误:

<if test="_parameter == '1' ">
    type=#{_parameter}
</if>

 

正确:

<if test='_parameter == "1" '>
    type=#{_parameter}
</if>

 

 

posted @ 2017-03-03 22:15  开拖拉机的蜡笔小新  阅读(569)  评论(0编辑  收藏  举报