首先看原來代碼java
<insert id="insert" parameterType="Class" > <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into allocate_order (allocate_code, created_at, create_user, updated_at, update_user, dr, ts, version) values (#{code,jdbcType=VARCHAR}, #{createdAt,jdbcType=TIMESTAMP}, #{createUser,jdbcType=VARCHAR}, #{updatedAt,jdbcType=TIMESTAMP}, #{updateUser,jdbcType=VARCHAR}, #{dr,jdbcType=CHAR}, #{ts,jdbcType=TIMESTAMP}, #{version,jdbcType=INTEGER}) </insert>
在字段肯定,可是在沒有值的時候,咱們須要給他們添加默認值,更改後代碼爲spa
<insert id="insert" parameterType="Class" > <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into allocate_order (dr,allocate_code,create_user,update_user,version) values ( <choose> <when test="dr != null and dr != '' "> #{dr,jdbcType=CHAR}, </when> <otherwise> '1', </otherwise> </choose> <choose> <when test="code != null and code != '' "> #{code,jdbcType=VARCHAR}, </when> <otherwise> '', </otherwise> </choose> <choose> <when test="createUser != null and createUser != '' "> #{createUser,jdbcType=VARCHAR}, </when> <otherwise> '', </otherwise> </choose> <choose> <when test="updateUser != null and updateUser != '' "> #{updateUser,jdbcType=VARCHAR}, </when> <otherwise> '', </otherwise> </choose> <choose> <when test="version != null and version != '' "> #{version,jdbcType=INTEGER} </when> <otherwise> 1 </otherwise> </choose>) </insert>
這裏是用了choose標籤when標籤和otherwise標籤,結合使用能夠針對不一樣狀況做出反應code
下面貼一個比較典型的操做 一個choose標籤下能夠有多個狀況,相似在判斷的時候的if ,else if,else這些it
<select id="findUserInfoByOneParam" parameterType="Map" resultMap="UserInfoResult"> select * from userinfo <choose> <when test="searchBy=='department'"> where department=#{department} </when> <when test="searchBy=='position'"> where position=#{position} </when> <otherwise> where gender=#{gender} </otherwise> </choose> <if test="gender!=null"> and gender=#{gender} <span style="white-space:pre"> </span></if> </select>