zoukankan      html  css  js  c++  java
  • mybatis基础(二)

    一.模糊查询

      1.select * from studentinfo where stuname like '%'  #{stuname}  '%'   

        注意:'%'和#{stuname}之间最好留有空格,否则可能会出现问题

      2.select * from studentinfo where stuname like concat('%',#{stuname},'%')

      3.select * from studentinfo where stuname like '%${stuname}%'  

        基本被排除在程序中,因为这种模糊查询容易被sql注入

    二.智能标签

      1.智能标签<where>和<if>

    select * from  studentinfo

      <where>
            <if test="stuno!=null">
               and stuno=#{stuno}
            </if>
         </where>

    通常<where>标签和<if>标签联合使用,当<where>标签中存在sql片段时(或是有东西时)才会在之前的sql后拼接出where ,且当where后跟随的是and是或自动将and删除

    如上:当if条件成立时: select * from  studentinfo where stuno=#{stuno}

       当where条件不成立时:select * from  studentinfo

      2.智能标签choose

        select * from studentinfo 

            <where> 
                <choose> 
                    <when test="stuName!=null"
                        and stuName like '%' #{stuName} '%' 
                    </when> 
                    <when test="stuAge!=null"
                        and stuAge>#{stuAge} 
                    </when> 
                    <otherwise> 
                         and 1=2 
                    </otherwise> 
                </choose> 
            </where> 
        这个标签相当于Java中的switch-case
      3.智能标签foreach
        select * from studentinfo 
            <where> 
                <if test="array.length>0"
                    stuid in 
                    <foreach collection="array" open="(" close=")" separator="," item="stuno"
                        #{stuno} 
                    </foreach> 
                </if
            </where> 
    collection:表示传入参数的类型,open表示开始符号,close表示结束符号,separator表示每一列之间的分隔符,item表示每一列的别名
     
      4.智能标签foreach List<StudentInfo>
      select * from studentinfo 
            <where> 
                <if test="list.size>0"
                    stuid in 
                    <foreach collection="list" open="(" close=")" separator="," item="stu"
                        #{stu.stuId} 
                    </foreach> 
                </if
            </where> 
    与上一个类似,区别在于集合中的项变成了一个实体
     
    三.当传入参数为零散的项时(使用索引号查询)
      DAO中的方法:
         public List<Emp> findByCondition(String name,int age);
      映射文件
           select * from emp where name like '%' #{0} '%' and age>#{1}

        

  • 相关阅读:
    [学习]利用SqlDataAdapter Insertcommand 获取刚新增的自动编号ID值
    [转]下拉框OnChange触发文本框值变化
    .NET伪静态使用以及和纯静态的区别
    Java之替换“\n”符号 Binary
    【转载】三种东西永远不要放到数据库里 Binary
    如何为Android Spinner设置一个初始值(How to make an Android Spinner with initial text “Select One”)? Binary
    Android之SQLite列操作 Binary
    Android——调用系统相册 Binary
    Android——用XML的selector实现按钮多态 Binary
    keystore信息的查看 Binary
  • 原文地址:https://www.cnblogs.com/wy0119/p/7689964.html
Copyright © 2011-2022 走看看