Mybatis使用大全

1. 与 #区别  一般#是代表sql语句中一些变量,select * from table1 id=#{id},替换成select * from id=?,我的理解是替换成占位符,所以可以避免sql注入 一般用于替换表、数据库的属性,select * from ${tableName},替换成select * from tableName(传入的参数),这个是硬拼sql语句,不能避免sql注入。
例子:

A findAById(@Param("tableName") String tableName, @Param("Id") long Id) throws SQLException;
 <select id="A" resultType="com.entity.A">
    <include refid="QUERY_ALL_COLUMN"/>
    FROM **${tableName}**
        WHERE id = #{Id}
        ORDER BY id desc
 </select>

2.动态sql片
mybatis中比较好用的就是动态sql片,尤其对于大量字段的select,可以将这些字段封装成一个sql片,其他在使用的时候就直接利用直接饮用就行
例子

<sql id="QUERY_ALL_COLUMN">
        SELECT
        id,
        order_id       AS orderId,
        create_time    AS createTime,
        update_time    AS updateTime
</sql>

<select id="" resultType="">
<include refid="QUERY_ALL_COLUMN"/>
from table1
</select>

3.批量插入
对于插入,一次性插入N条,需要不使用批量插入,每一条都使用insert into table(field1,field2..) values(value1,value2…),耗时是巨大的,所以mybatis使用批量插入
foreach为迭代标签,属性主要有 item,index,collection,open,separator,close

    item表示集合中每一个元素进行迭代时的别名.
    index指定一个名字,用于表示在迭代过程中,每次迭代到的位置
    open表示该语句以什么开始
    separator表示迭代之间的分隔符
    close表示以什么结束

例子

 int batchInsert(@Param("list") List<User> list);
  <insert id="batchInsert" parameterType="java.util.List">
        insert into user(
            id,
            stu_id,
            stu_name
            stu_age
        ) values
        <foreach collection="list" index="index" item="item" separator=",">
            (
                #{item.Id},
                #{item.userId},
                #{item.userName},
                #{item.userAge}
            )
        </foreach>

    </insert>

4.
一般对于在where中可能为空的字段的,会出现这样的问题,“select * from user where”,那这种肯定是无效的sql,为了解决这个问题,用
例子

<select id="",resultType="">
select * from ${tableName}
<where>
 <if test="id != null">
        id=#{id}
  </if>
  <if test="user!=null">
      user=#{user}
   </if>
</where>
</select>

5.if-else
对于if-else,mybaits使用

<choose>
    <when test="...">
    where XXX
    </when>
    <otherwise>
    where YYY
    </otherwise>
</choose>

 <select id="findCount" resultType="java.lang.Integer">
        SELECT count(DISTINCT id) AS Num FROM ${tableName}
        <choose>
            <when test="name!=null">use index(idx_name)</when>
            <otherwise>use index(idx_age)</otherwise>
        </choose>
        WHERE user_id = #{userId}
</select>

猜你喜欢

转载自blog.csdn.net/zhanggirlzhangboy/article/details/80881500
今日推荐