開發中,sql拼接很常見,所以說一下動態sql:
1 | if |
2 | chose,when,otherwise |
3 | where,set |
4 | foreach |
用法解析(現有一張users表 內有id username age 三個字段):
<!--查詢所有用戶,傳遞參數type,如果值為0,按照年齡升序排序,如果為1則按照年齡降序排序,否則按照ID排序--><!--choose when otherwise的用法 大致相當于case when default--><select id="getUserListByType" resultType="User">select * from users<choose><when test="type==0">order by age asc</when><when test="type==1">order by age desc</when><otherwise>order by id asc</otherwise></choose></select><!--根據多個id查詢用戶 if where foreach的用法--><select id="getUserListByIds" resultMap="User">select * from users<where>-- if判斷 如果傳進去的參數ids不為空<if test="ids!=null and ids==''">and id in-- foreach循環ids 以逗號為分隔符 以ids這個字符串中的'('為開始 ')'為結果<foreach collection="ids" item="id" open="(" close=")" separator=",">#{id}</foreach></if></where></select><!--修改用戶信息,如果某字段為null,則不修改這個字段 set的用法--><select id="updateUser">update users<set><if test="username!=null and username!=''">username = #{username}</if><if test="age!=null">age = #{age}</if></set></select>
?
我們還可以把重復的sql抽取出來,作為公用的sql片段:
定義sql片段:
<!-- sql片段 建議:對單表進行sql片段的抽取,方便重用抽取時不包含where--><sql id="findUserSql"><if test="userCustomer!=null"><if test="userCustomer.age!=null">and user.age=#{userCustomer.age}</if><if test="userCustomer.username!=null and userCustomer.username!=''">and user.username like '$%{userCustomer.username}%'</if></if></sql>
使用sql片段:
<!-- 動態sql --><select id="findUserCount" parameterType="com.zy.domain.User" resultType="int">select count(*) from users-- where 可自動去除條件中的第一個and<where><include refid="findUserSql"></include></where></select>
?