zoukankan      html  css  js  c++  java
  • Mybatis 笔记

    1.# 和 $ 的区别

    1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".
      
    2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,  如果传入的值是id,则解析成的sql为order by id.
      
    3. #方式能够很大程度防止sql注入。
      
    4.$方式无法防止Sql注入。

    5.$方式一般用于传入数据库对象,例如传入表名.
      
    6.一般能用#的就别用$.


    MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

    2.String 传参  使用$取值

    mybatis传入字符串参数时,使用${}取值会默认找传入参数类型里对应字段的getter/setter方法,会报 There is no getter for property named 'ids' in 'class java.lang.String'。的异常

    解决办法有两种
    1、在参数上使用@param注解

    2、在xml的里用”_parameter” 代表参数(#{_parameter})

    3. 如<if>参数判断传入数字字符串

    会把字符串尝试向数字类型转换

    1.解决方法:

    <if test="fmodel  == 2 ">
            and fmodel = #{fmodel}
    </if>
    

     2.解决方法:

    <if test="fmodel  == '2'.toString() ">
            and fmodel = #{fmodel}
    </if>

    4.插入数据,返回主键id

     <insert id="insertMessageBorad" parameterType="com.bphl.message.model.po.M_T_MessageBorad">
            <selectKey resultType="java.lang.String" order="BEFORE" keyProperty="fid">
                select uuid() fid from dual
            </selectKey>
            insert into m_t_messageBorad(fid,fcontent,ftype)
            values(#{fid},#{fcontent},''},#{ftype})
        </insert>
    

     service层获取主键id: m_t_messageRorad.getFid();

    5.常见动态标签使用

    a.  <if> 判断使用该值是否为空

      <if test="fname != null and fname != ''">
                and a.ftitle like '%${fname}%'
            </if>
    

     b.<choose> 使用,相当于if,else

     <choose>
                <when test="ftimeFlag == null or ftimeFlag == '1'">
                    order by a.fcreatetime DESC
                </when>
                <otherwise>
                    order by a.fcreatetime ASC
                </otherwise>
        </choose>
    

     c.<foreach>的使用

     <foreach collection="list" separator="," open="(" close=")" item="value">
                    #{value}
       </foreach>
    

     collection : 需要遍历的集合 (这里的取值不需要$或# 直接写参数名称)

    open:遍历开始添加的字符串

    close:遍历结束添加的字符串

    separator:每个值之间的分割符

    item:遍历出来的值

    5.<foreach>动态拼接问题

    select fid from test where  fid in
     <foreach collection="list" item="item" separator="," open="(" close=")">
                    #{item}
     </foreach>

    当集合为空时回报错,sql语句会拼接成select fid from test where fid in(),需要先判断集合是否为空

    select fid from test where 1= 1
     <if test="list != null and list.size > 0">
               fid in
            <foreach collection="list" item="item" separator="," open="(" close=")">
                    #{item}
     </foreach>
      </if>

     

  • 相关阅读:
    普通平衡树(treap与splay模板)
    NOIP2009T4 靶形数独
    单调队列模板
    NOIP2010引水入城
    数差
    NOIP2016DAY2T1 组合数问题
    NOIP2016 D2T3 愤怒的小鸟
    NOIP双栈排序
    膜拜
    斐波那契数列
  • 原文地址:https://www.cnblogs.com/lin-mumu/p/10921858.html
Copyright © 2011-2022 走看看