动态拼接实现有条件的插入
最近在做项目的时候遇到了一个很现实的问题
那就是根据场景不同,然后实现有条件的插入,说穿了就是当这列有数据的时候进行数据的插入,没有数据的时候自动忽略这列。
其实这些在mybatis的api中有涉及到,但是之前一直没有好好看,直到最近用到了才认真的看了看这块的内容。
- <!-- 新增部门人员 -->
- ? ? <insert id="addStaffForApp" parameterType="com.hivescm.org.dto.StaffForAppDto" >
- ? ? ? ? insert into base_department_staff
- ? ? ? ? <trim prefix="(" suffix=")" suffixOverrides="," >
- ? ? ? ? ? ? status,
- ? ? ? ? ? ? group_id,
- ? ? ? ? ? ? staff_code,
- ? ? ? ? ? ? realname,
- ? ? ? ? ? ? create_time,
- ? ? ? ? ? ? phone,
- ? ? ? ? ? ? is_temporary
- ? ? ? ? ? ? <if test="param.email !=null">
- ? ? ? ? ? ? ? ? email,
- ? ? ? ? ? ? </if>
- ? ? ? ? ? ? <if test="param.userId !=null">
- ? ? ? ? ? ? ? ? user_id,
- ? ? ? ? ? ? </if>
- ? ? ? ? ? ? <if test="param.sex !=null">
- ? ? ? ? ? ? ? ? sex,
- ? ? ? ? ? ? </if>
- ? ? ? ? </trim>
- ?
- ? ? ? ? <trim prefix="values (" suffix=")" suffixOverrides="," >
- ? ? ? ? ? ? #{param.status},
- ? ? ? ? ? ? #{param.groupId},
- ? ? ? ? ? ? #{param.staffCode},
- ? ? ? ? ? ? #{param.realname},
- ? ? ? ? ? ? #{param.phone},
- ? ? ? ? ? ? #{param.temporary}
- ? ? ? ? ? ? <if test="param.email !=null">#{param.email},
- ? ? ? ? ? ? </if>
- ? ? ? ? ? ? <if test="param.userId !=null">#{param.userId},
- ? ? ? ? ? ? </if>
- ? ? ? ? ? ? <if test="param.sex !=null">#{param.sex},
- ? ? ? ? ? ? </if>
- ? ? ? ?</trim>
- ? ? </insert>
这里头的trim相信就不用多说了,经常用来去空格。这个trim标签中有三个属性,prefix这个是表明了你要拼接sql的前缀,suffix这个则是表明了动态sql的后缀,suffixOverrides这个会帮助我去掉最后一个多出来的逗号。
mybatis插入语句
mybatis插入语句一般都是这样写
<!-- useGeneratedKeys="true"把新增加的主键赋值到自己定义的keyProperty(id)中 -->
- <insert id="insert" parameterType="xxx.xxx.xxx.xxx" keyProperty="id" useGeneratedKeys="true">
useGeneratedKeys
取值范围true|false 默认值是:false。- 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。
之前一直以为useGeneratedKeys="true"是让mysql数据库主键新增,其实是,插入语句后将id赋值给实体bean,即使用insert后,使用bean.getId()可以获得值,若是false,bean.getId()=null。
不管true还是false,数据库插入的数据,都会自动生成主键(前提是设置自动增长主键)。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。