动态标签有哪些?
按照官網的分類,MyBatis 的動態標簽主要有四類:if,choose (when, otherwise),trim (where, set),foreach。
(案例在spring-mybatis 工程中)
if —— 需要判斷的時候,條件寫在test 中
以下語句可以用<where>改寫
<select id="selectDept" parameterType="int" resultType="com.leon.crud.bean.Department">select * from tbl_dept where 1=1<if test="deptId != null">and dept_id = #{deptId,jdbcType=INTEGER}</if> </select>choose (when, otherwise) —— 需要選擇一個條件的時候
<select id="getEmpList_choose" resultMap="empResultMap" parameterType="com.leon.crud.bean.Employee"> SELECT * FROM tbl_emp e<where><choose><when test="empId !=null">e.emp_id = #{emp_id, jdbcType=INTEGER}</when><when test="empName != null and empName != ''">AND e.emp_name LIKE CONCAT(CONCAT('%', #{emp_name,jdbcType=VARCHAR}),'%')</when><when test="email != null ">AND e.email = #{email, jdbcType=VARCHAR}</when><otherwise></otherwise></choose></where> </select>trim (where, set)——需要去掉where、and、逗號之類的符號的時候。
注意最后一個條件dId 多了一個逗號,就是用trim 去掉的:
<update id="updateByPrimaryKeySelective"parameterType="com.leon.crud.bean.Employee">update tbl_emp<set><if test="empName != null">emp_name = #{empName,jdbcType=VARCHAR},</if><if test="gender != null">gender = #{gender,jdbcType=CHAR},</if><if test="email != null">email = #{email,jdbcType=VARCHAR},</if><if test="dId != null">d_id = #{dId,jdbcType=INTEGER},</if></set>where emp_id = #{empId,jdbcType=INTEGER} </update>trim 用來指定或者去掉前綴或者后綴:
<insert id="insertSelective" parameterType="com.leon.crud.bean.Employee"> insert into tbl_emp<trim prefix="(" suffix=")" suffixOverrides=","><if test="empId != null">emp_id,</if><if test="empName != null">emp_name,</if><if test="dId != null">d_id,</if></trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="empId != null">#{empId,jdbcType=INTEGER},</if><if test="empName != null">#{empName,jdbcType=VARCHAR},</if><if test="dId != null">#{dId,jdbcType=INTEGER},</if></trim> </insert>foreach —— 需要遍歷集合的時候:
<delete id="deleteByList" parameterType="java.util.List"> delete from tbl_emp where emp_id in<foreach collection="list" item="item" open="(" separator="," close=")">#{item.empId,jdbcType=VARCHAR}</foreach> </delete>動態SQL 主要是用來解決SQL 語句生成的問題。
?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
- 上一篇: 为什么需要动态SQL?
- 下一篇: mybatis-批量操作