##前言:因为项目的原因,会生成新的数据库表,而表名和大部分字段都是未知,所以sql用了大量的遍历,也没有实体类,数据都Map和List
一,单条插入获得id
//因为没有实体类所以自然无法用mybatis将id返回给实体类的方式,这里虽然是插入语句 但是用的标签是select,如不用select返回的是行数
sql执行完后加 select @@IDENTITY as saveHistory 便可得到新增得id
<select id="saveHistory" resultType="java.lang.Long">
insert into ${param2}
(CreateUser,
<foreach collection="param1.keys" item="key" close=")"
separator=",">
${key}
</foreach>
values
(#{param3},
<foreach collection="param1.values" item="value"
close=")" separator=",">
#{value}
</foreach>
select @@IDENTITY as saveHistory
</select>
二,多条插入获得id
//同样是插入语句用select,单用 select @@IDENTITY只能获得最新生成得id 无法获取全部得id,这种是使用创建临时表,将生成得id存入临时表,再查询临时表得方式获取新增得所有id,数据库用的sql server,其他数据库没测试过。
<select id="saveCompensationFileList" resultType="java.lang.Long">
create table #t(id int)
<foreach collection="param1" item="items" index="index">
insert into ${param2}
<foreach collection="items.keys" item="key" open="(" close=")"
separator=",">
${key}
</foreach>
output inserted.id into #t
values
<foreach collection="items.values" item="value" open="("
close=")" separator=",">
#{value}
</foreach>
</foreach>
select * from #t
</select>
三,判断Map类型数据是否为空
//maps.containsKey(key)使用此语句较好,以前直接使用得 != null判断有时候有问题
update ${dbname}
<set>
<foreach collection="maps.keys" item="key" open="" close=""
separator=",">
<if test="maps.containsKey(key)">
${key} = #{maps.${key}}
</if>
</foreach>
</set>
where UserId=#{UserId}
四,指定列去重
//PropertyInfoId去重的列,根据CreateDate时间获取时间最大的那条数据
SELECT * FROM PropertySafetyInfo a where
not exists(select 1 from PropertySafetyInfo where
PropertyInfoId=a.PropertyInfoId and CreateDate<a.CreateDate)