mybatis常用语法

mybatis判断是否为空或null

<select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
    <if test="studentName!=null and studentName!='' ">  
        WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')   
    </if>  
</select>

mybatis判断集合为空或者元素个数为零

<if test="mlhs != null and mlhs.size() != 0">
  and t.mlh_name not in  
  <foreach collection="mlhs" item="item1" open="(" close=")" index="i" separator=","> 
    #{item1,jdbcType=VARCHAR}
  </foreach>
</if>

mybatis 插入多条记录

<insert id="addSubPoints" parameterType="java.util.List">
    INSERT INTO
    ORDERPOINT(ORDERID,POINTNAME,LAT,LON)
    VALUES
    <foreach collection="list" item="item" index="index"
        separator=",">
        (#{item.orderId},#{item.pointName},#{item.lat},#{item.lon})
    </foreach>
</insert>

mybatis使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:

<update id="updateStudent" parameterType="StudentEntity">     
    UPDATE STUDENT_TBL      
    <set>     
        <if test="studentName!=null and studentName!='' ">     
            STUDENT_TBL.STUDENT_NAME = #{studentName},      
        </if>     
        <if test="studentSex!=null and studentSex!='' ">     
            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
        </if>     
        <if test="studentBirthday!=null ">     
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
        </if>     
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
        </if>     
    </set>     
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
</update>   

Mybatis自动生成key值(selectKey和useGeneratedKeys)

如果数据库支持自增长主键字段(比如MySQL、sql server)设置useGeneratedKeys=”true”和keyProperty,这样就可以插入主键id值
Oracle则不支持自增长id,设置useGeneratedKey=”false”,如果设置true则会有报错信息。

<!-- 插入新的问题件 -->
<!-- useGeneratedKeys="true"把新增加的主键赋值到自己定义的keyProperty(id)中 -->
<insert id="insert" parameterType="jw.base.entity.WrongRecApply" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
    insert into tb_wrong_rec_apply (num, cid,
        `type`, `describe`, solution,
        seller_tel, seller_qq, seller_email,
        buyer_tel, buyer_qq, buyer_email,
        submit_time, update_time, r_wrong_id,
        ext1, ext2, img,state
      )
     values (#{num,jdbcType=VARCHAR}, #{cid,jdbcType=INTEGER},
        #{type,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, #{solution,jdbcType=VARCHAR},
        #{sellerTel,jdbcType=VARCHAR}, #{sellerQq,jdbcType=VARCHAR}, #{sellerEmail,jdbcType=VARCHAR},
        #{buyerTel,jdbcType=VARCHAR}, #{buyerQq,jdbcType=VARCHAR}, #{buyerEmail,jdbcType=VARCHAR},
        #{submitTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{rWrongId,jdbcType=INTEGER},
        #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR}, #{img,jdbcType=LONGVARBINARY},#{state,jdbcType=INTEGER}
    )
</insert>

mybatis的trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。

where例子的等效trim语句:

<!-- 查询学生list,like姓名,=性别 -->     
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <trim prefix="WHERE" prefixOverrides="AND|OR">     
        <if test="studentName!=null and studentName!='' ">     
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
        </if>     
        <if test="studentSex!= null and studentSex!= '' ">     
            AND ST.STUDENT_SEX = #{studentSex}      
        </if>     
    </trim>     
</select>     

set例子的等效trim语句:

<!-- 更新学生信息 -->     
<update id="updateStudent" parameterType="StudentEntity">     
    UPDATE STUDENT_TBL      
    <trim prefix="SET" suffixOverrides=",">     
        <if test="studentName!=null and studentName!='' ">     
            STUDENT_TBL.STUDENT_NAME = #{studentName},      
        </if>     
        <if test="studentSex!=null and studentSex!='' ">     
            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
        </if>     
        <if test="studentBirthday!=null ">     
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
        </if>     
        <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
        </if>     
    </trim>     
    WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
</update>     

choose (when, otherwise)

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

if是与(and)的关系,而choose是或(or)的关系。

<!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->     
<select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
    SELECT * from STUDENT_TBL ST      
    <where>     
        <choose>     
            <when test="studentName!=null and studentName!='' ">     
                    ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
            </when>     
            <when test="studentSex!= null and studentSex!= '' ">     
                    AND ST.STUDENT_SEX = #{studentSex}      
            </when>     
            <when test="studentBirthday!=null">     
                AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
            </when>     
            <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
                AND ST.CLASS_ID = #{classEntity.classID}      
            </when>     
            <otherwise>     
                      
            </otherwise>     
        </choose>     
    </where>     
</select>     

foreach

对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。

参数为list实例的写法:

public List<StudentEntity> getStudentListByClassIDs(List<String> classList);
<select id="getStudentListByClassIDs" resultMap="studentResultMap">     
    SELECT * FROM STUDENT_TBL ST      
     WHERE ST.CLASS_ID IN       
     <foreach collection="list" item="classList"  open="(" separator="," close=")">     
        #{classList}      
     </foreach>         
</select>     

参数为Array实例的写法:

public List<StudentEntity> getStudentListByClassIDs(String[] ids);
<select id="getStudentListByClassIDs" resultMap="studentResultMap">     
    SELECT * FROM STUDENT_TBL ST      
     WHERE ST.CLASS_ID IN       
     <foreach collection="array" item="ids"  open="(" separator="," close=")">     
        #{ids}      
     </foreach>     
</select>   

mybatis ${}与#{}的区别

简单来说#{} 解析的是占位符?可以防止SQL注入, 比如打印出来的语句select * from table where id=?,然而${} 则是不能防止SQL注入打印出来的语句 select * from table where id=2 实实在在的参数。

最简单的区别就是${}解析穿过来的参数值不带单引号,#{}解析传过来参数带单引号。

最后总结一下必须使用$引用参数的情况,那就是参数的int型的时候,必须使用$引用。