mybatis中的$和#区别

版权声明:转载请注明出处 https://blog.csdn.net/h2604396739/article/details/84316633

提前总结:
1mybatis中$取值不会自动给你转为string类型,即不会给你自动在值得两侧加双引号,用#取值会自动转为String,自动加双引号,这个大家都知道。

2如果实际传的是个map,parameterType可以声明为"java.lang.String",但此时取值只能使用#,不能使用$
3下面的是我这次遇到的坑:当xml中parameterType声明为"java.lang.String"时,就一定不可以用$取值,只能用#,因为#才能确保你取到的值是String,否则会报
        ### The error occurred while setting parameters

挖坑填坑经历如下:
AlarmCountResultMapper中:
    Integer deleteAlarmCountResultLogical(Map<String, String> map);
xml文件:
    <update id="deleteAlarmCountResultLogical" parameterType="java.lang.String">
        update alarm_count_result set

        <if test="status != null and status != '' ">
            status = #{status}
        </if>
         where  id in ${id}
    </update>
        此时会报错,id取到值不是(12),报错内容:
        ### The error occurred while setting parameters
### SQL: update alarm_count_result set                        status = ?                    where  id in com.ruisitch.bi:rsbi:war:4.0
        报上面错的原因,猜测是因为声明了parameterType="java.lang.String",而$的取值结果是不会自动转为String,所以在用$取值的时候直接报错,即如果声明parameterType为java.lang.String,用$取值一定会报错

    但是如果修改为下面,即取id的值使用#,能取到值,但是为String类型的(12)但是语法不对了,自动转为String,sql实际为:
    update alarm_count_result set                        status = 2                   where  id in “(12)”
    即“”在括号的外边,这当然也是错误的
        <update id="deleteAlarmCountResultLogical" parameterType="java.lang.String">
        update alarm_count_result set

        <if test="status != null and status != '' ">
            status = #{status}
        </if>
         where  id in #{id}
    </update>
    正确的使用方式如下将parameterType声明为:java.util.Map,id的取值方式使用
    <update id="deleteAlarmCountResultLogical" parameterType="java.util.Map">
        update alarm_count_result set

        <if test="status != null and status != '' ">
            status = #{status}
        </if>
         where  id in ${id}
    </update>

    如果parameterType="java.lang.String",取值的时候都是采用#方式来取值,这种方式也是可以的
    public  void  deleteAlarmCountResultPhysicalByTime(String time){
        map.put("id","12");
        map.put("status","2");
        mapper.deleteAlarmCountResultPhysicalByTime(map);
    }
    AlarmCountResultMapper中:
        void deleteAlarmCountResultPhysicalByTime(HashMap<String,String> map);

     <delete id="deleteAlarmCountResultPhysicalByTime" parameterType="java.lang.String">
        delete from  alarm_count_result
        where add_time <![CDATA[ < ]]> #{add_time}
        and status=#{status}
    </delete>

猜你喜欢

转载自blog.csdn.net/h2604396739/article/details/84316633