溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

myBatis中實用技巧

發布時間:2020-06-28 18:41:36 來源:網絡 閱讀:444 作者:沙漏半杯 欄目:編程語言

技巧一:


把查詢的字段,查詢的條件單獨寫在一起,使用 <sql></sql>標簽定義,使用<include></include>標簽引用

<!-- 查詢的字段 -->

<sql id="Base_Column_List" >

? ? id, name

</sql>

?

<!-- 查詢的條件 -->

<sql id="QUERY">

? <where>

? ? <if test="id != null">

? ? ? ?AND id = #{id,jdbcType=INTEGER}

? ? </if>

? ? <if test="name != null">

? ? ? ?AND name= #{name,jdbcType=VARCHAR}

? ? </if>

? </where>

</sql>

?

<!-- 查詢語句 -->

<select id="selectByCondition" resultMap="baseResultMap">

? ?select?

? ?

? ?<!-- 引入查詢的字段 -->

? ?<include refid="Base_Column_List" />

? ?

? ?from student

?

? ?<!-- 引入查詢的條件 -->

? ?<include refid="QUERY"></include>

</select>

?


技巧二:


大于小于號轉義

<!-- 第一種方式:使用轉義字符 -->

<if test="createTime != null">

?

? <!--? ?&gt; -> 大于號(>)? ?-->

? create_time &gt;= #{createTime ,jdbcType=DATE}

?

</if>

?

<if test="updateTime != null">

?

? <!--? ?&lt; -> 小于號(<)? ?-->

? update_time &lt;= #{updateTime ,jdbcType=DATE}

?

</if>

?

?

<!-- 第二種:xml格式 -->

<if test="createTime != null">

?

? <![CDATA[

? ? ? create_time >= #{createTime ,jdbcType=DATE}

? ]]>

?

</if>

?

<if test="updateTime != null">

?

? <![CDATA[

? ? ? update_time <= #{updateTime ,jdbcType=DATE}

? ]]>

?

</if>

?


技巧三:


插入時返回自增的主鍵id

<!-- myBatis中關鍵點就是在 insert 標簽內添加 useGeneratedKeys 和 keyProperty屬性 -->

?

<!-- useGeneratedKeys:如果插入的表以自增列為主鍵,則允許 JDBC 支持自動生成主鍵,并可將自動生成的主鍵返回 -->

?

<!-- keyProperty:對應的主鍵的對象 -->

?

<insert id="insertSelective" parameterType="com.test.student" useGeneratedKeys="true" keyProperty="id">

? ? <!-- 這里寫插入 sql -->

</insert>

?

?

<!-- java代碼中關鍵點就是,返回的自增主鍵不是調用的 insertSelective 方法返回結果 -->

?

<!-- 返回結果為影響行數,正確的獲取方式是在入參的 student 對象中,使用 getId() 方法得到 -->

?

<!-- 這只是舉例,具體的對象和對象中的id屬性的getter方法不一樣 -->

?


技巧四:


在插入前/插入后查詢獲取某個字段的值,并且使用在緊接著的第二條 sql 中

<!-- 場景描述:一個置頂功能,設置置頂的時候需要得到最大的置頂數,加一后設置為本次置頂數 -->

?

?

<!-- 在顯示置頂的時候是按照倒序排列,越往后點擊了置頂的數據顯示的越前面 -->

?

<!-- 設置置頂 -->

<update id="updateTop">

? ??

? ? <!-- 更新前查詢出最大的置頂數,并且加一后返回出來 -->

? ? <!-- 注: -->

? ? <!--? ? 1. 更新前/更新后:BEFORE/AFTER -->

? ? <!--? ? 2. 這里是在有很多數據后添加的排序字段,添加排序字段后,老數據那一列都是null -->

? ? <!--? ? ? ?則在此處使用了 COALESCE 函數做了一個小處理,如果為null就取值0 -->

?

<selectKey keyProperty="top_sort" order="BEFORE" resultType="java.lang.Integer">

select COALESCE(max(top_sort),0) + 1 from table

</selectKey>

? ? <!-- 設置置頂主 sql -->

? ? <!-- 注: -->

? ? <!--? ? 1. 下面 sql 中的 #{top_sort} 是取的上面 sql中的結果 -->

?

update table

top_sort = #{top_sort}?

<if test="update_time!=null">

,update_time=#{update_time}

</if>

<if test="update_user!=null">

,update_user=#{update_user}

</if>

where id = #{id}

</update>

?


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女