mybatis的一個比較先進的思想是把Sql語句寫在了配置xml文件(也支持注解),通過配置文件的方式,免去了一般軟件開發的硬編碼,當業務需求改變的時候,只需要更改sql語句即可!
下面是個人在學習mybatis動態insert語句的筆記,留着參考!
在寫insert子句的時候,由於不知道需要插入多少字段,mybatis通過prefix,suffix,suffixOverrides很好的解決了該問題,實現了動態insert語句。
<insert id="insertSelective" parameterType="com.bootdo.system.domain.LogDO"> insert into sys_log <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="userId != null"> user_id, </if> <if test="username != null"> username, </if> <if test="operation != null"> operation, </if> <if test="time != null"> time, </if> <if test="method != null"> method, </if> <if test="params != null"> params, </if> <if test="ip != null"> ip, </if> <if test="gmtCreate != null"> gmt_create, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=BIGINT}, </if> <if test="userId != null"> #{userId,jdbcType=BIGINT}, </if> <if test="username != null"> #{username,jdbcType=VARCHAR}, </if> <if test="operation != null"> #{operation,jdbcType=VARCHAR}, </if> <if test="time != null"> #{time,jdbcType=INTEGER}, </if> <if test="method != null"> #{method,jdbcType=VARCHAR}, </if> <if test="params != null"> #{params,jdbcType=VARCHAR}, </if> <if test="ip != null"> #{ip,jdbcType=VARCHAR}, </if> <if test="gmtCreate != null"> #{gmtCreate,jdbcType=TIMESTAMP}, </if> </trim> </insert>