做添加时,部分字段有值,没值的字段不添加,这就是动态添加,使用 trim 标签就可以实现。
<insert id="insertSysUser" parameterType="com.mydemo.entity.SysUser"> insert into sys_user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null and id != ''"> id, </if> <if test="username != null and username != ''"> username, </if> <if test="realName != null and realName != ''"> real_name, </if> <if test="idcard != null and idcard != ''"> idcard, </if> create_time </trim> <trim prefix="values(" suffix=")" suffixOverrides=","> <if test="id != null and id != ''"> #{id, jdbcType = VARCHAR}, </if> <if test="username != null and username != ''"> #{username, jdbcType = VARCHAR}, </if> <if test="realName != null and realName != ''"> #{realName, jdbcType = VARCHAR}, </if> <if test="idcard != null and idcard != ''"> #{idcard, jdbcType = VARCHAR}, </if> now() </trim> </insert>
最终结果:insert into sys_user ( id, username, real_name, idcard, create_time ) values( ?, ?, ?, ?, now() )
trim标签属性含义:
属性 | 描述 |
prefix | 给sql语句拼接的前缀 |
suffix | 给sql语句拼接的后缀 |
prefixesToOverride | 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixesToOverride属性指定,假设该属性指定为”AND”,当sql语句的开头为”AND”,trim标签将会去除该”AND” |
suffixesToOverride | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixesToOverride属性指定 |