MyBatisの研究ノート4

録画動的SQLの共通のタグ:

1.where

条件は、一般に、データ加算演算として使用されています

例:

 <select id="selectByRoleId" resultMap="resource">
        select * from resource <where> role_id = #{roleId} </where>

2.Ifは

一般的に、変更、クエリとして使用、またはデータスプライシング条件の一部を削除します。

条件のテストフィールドを分析します

例:

<select id="findCountByContditon" resultType="int" parameterType="com.example.demo.po.User">
        select coalesce(count(id),0) from user <where> <if test="name != null and name != ''"> name like #{name} </if> <if test="createTime != null"> and create_time &lt; #{createTime} </if> </where> </select>

問題がある上記のSQLは、条件が満たされていない場合、その名前は、creatTime条件は、SQLエラー、満足しています。一般的に、1 = 1であれば前ここ条件下で添加される場合、複数存在するか否かを決定します。

<select id="findCountByContditon" resultType="int" parameterType="com.example.demo.po.User">
        select coalesce(count(id),0) from user <where> 1=1 <if test="name != null and name != ''"> and name like #{name} </if> <if test="createTime != null"> and create_time &lt; #{createTime} </if> </where> </select>

3.foreach

一般的にバルクデータを追加するために使用

フィールド一般コレクションリスト、配列、マップタイプ、渡されたパラメータの値

セパレータデリミタフィールド値、すなわち、どのような分割

各項目フィールドのエイリアスは、ループエレメントであります

1サイクル目の各添字インデックスフィールド値

オープンフィールド値のプレフィックス値

近いサフィックス値フィールド値

例:

<insert id="saveAll" parameterType="java.util.List">
        insert into user(name,role_id,password) values <foreach collection="users" separator="," item="user" index="index" > ( #{user.name}, #{user.roleId}, #{user.password}) </foreach> </insert>

4.set

しばしば一緒に表示された場合、一般的に、修正されたデータに使用されます

<update id="updateByCondition">
        update user
        <set> <if test="name != null and name != ''"> name = #{name}, </if> <if test="password != null and password != ''"> password = #{password}, </if> <if test="createTime != null"> create_time = @{createTime} </if> </set> where id = #{id} </update>

5.include

一般的には、一定のフィールド抽出として使用されています

<sql id="user_columns">
        id, name,role_id,password,create_time,update_time
    </sql>

<select id="selectById" resultMap="user">
        select <include refid="user_columns"/> from user where id = #{id} </select>

6.trim

プレフィックス値フィールドの接頭辞が追加されます

サフィックスを追加サフィックス値フィールド

prefixOverridesフィールド削除プレフィックス値

suffixOverridesフィールドの削除サフィックス値

<update id="updateByCondition">
        update user  set
        <trim suffixOverrides=","> <if test="name != null and name != ''"> name = #{name}, </if> <if test="password != null and password != ''"> password = #{password}, </if> <if test="createTime != null"> create_time = @{createTime}, </if> </trim> where id = #{id} </update>

パスワードが空の場合、もう一方は空ではありません。SQLはなり

更新ユーザーセット名=#{名前}、CREATE_TIME =#{CREATETIME} ID =#{ID}

 出典:http://www.1994july.club/seo/

おすすめ

転載: www.cnblogs.com/1994july/p/12037504.html
おすすめ