mappers文件中的#{}语法与${}语法的区别:
默认情况下, #{}语法会促使MyBatis生成PreparedStatement属性并且使用PreparedStatement的参数(=?)来设置值。如果你想直接将未更改的字符串代入到sql中,可以使用${}。
mybatis批量插入:
使用INSERTINTO [TABLE]([FIELD],[FIELD]...)VALUES([VALUE],[VALUE]...),([VALUE],[VALUE]...)... 比使用insert into XXX values(XX),insert into XXX values(XXX),insert into XXX values(XXX)效率要高。
但是,在一条命令SQL引擎默认是一次最多插入1000笔记录,最多2100个字段参数。所以插入的时候还要处理一下:
public int insertPartList(List<Part> parts){
int rs=0;
int dealNum = 520;// 每次批处理条数
for(int i=0,s=0;i<parts.size()/dealNum;i++,s+=dealNum)
rs+=getSqlSession().insert("insertPartList",parts.subList(s,s+dealNum));
// 处理剩余部分
int afterNum = (parts.size()/dealNum)*dealNum;
if(parts.size()-afterNum >0)
rs+=getSqlSession().insert("insertPartList",parts.subList(afterNum,parts.size()));
return rs;
}
<insert id="insertBatch" useGeneratedKeys="true" parameterType="java.util.List"> <selectKey resultType="long" keyProperty="id" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> insert into table1 (<include refid="Base_Column_List" />) values <foreach collection="list" item="item" index="index" separator="," > (#{item.name},#{item.sex},#{item.address},#{item.telephone}) </foreach> </insert>
可以用union all来实现批量插入。
例如:
insert into TABLE(XX,XX,XX)select 'xx','xx','xx' union all select 'xx','xx','xx' union all select 'xx','xx','xx' ...
先拼装好语句再动态传入insert into TABLE(XX,XX,XX)后面部分
<insert id="insertBatch2" useGeneratedKeys="true" parameterType="java.util.List"> INSERT INTO table1 (<include refid="Base_Column_List" />) VALUES <foreach collection="list" item="item" index="index" separator="union all"> select #{item.name,jdbcType=VARCHAR},#{item.sex,jdbcType=VARCHAR},#{item.address,jdbcType=VARCHAR},#{item.telephone,jdbcType=VARCHAR} from dual </foreach> </insert>