2019独角兽企业重金招聘Python工程师标准>>>
方法一:script标签方式
@Insert("<script>insert into xxx (channelId,siteId) " +"values " +"<foreach collection=\"list\" item=\"item\" index=\"index\" separator=\",\" >(#{item.channelId},#{item.siteId})" +"</foreach></script>")public int addxxx(@Param("list")List<xxxBean> xxxBean);
方法二:SQL直接生成 注意该方法经过实际使用出现问题!!!!!!!!!!!!!!!!!!!!.
当批量插入的字段中包涵中文时,这样拼接的中文参数是没有' '包裹的.存储的时候就会出错.因此该方式只适合存储字段中只有数字的情况,当然也可以在拼接的时候将''拼接上,但是很容易出错
@InsertProvider(type=SqlProvider.class,method="addccc")
public int addxxxx(@Param("aBean")List<xxxBean> xxxBean);
public String addccc(Map<String,Object> map){List<xxxBean> channelList = (List<xxxBean>)map.get("aBean");StringBuilder sql = new StringBuilder("insert into table").append(" (channelId, siteId) ").append("values ");for (int i=0;i<channelList.size();i++) {sql.append("(").append(channelList.get(i).getChannelId()).append(",").append(channelList.get(i).getSiteId()).append(")");if(i < channelList.size() - 1){sql.append(",");}}return sql.toString();}
方法三: 拼接下标取值的SQL 试用了下,没问题,有待观察
需要得到以下格式的SQL:
insert into user (name,sex)
values
(#{userBeans[0].name},#{userBeans[0].sex}),(#{userBeans[1].name},#{userBeans[1].sex})
public String insertUserByList(Map<String,Object> map){List<User> alarmInBeans = (List<userBeans>)map.get("userBeans");StringBuilder sql = new StringBuilder("insert into user (name, sex) values");// #{userBeans[0].name}// 拼接出这样的格式的最终sql通过#{}取值// 需要用来格式化的字符串模板MessageFormat mf = new MessageFormat("(#'{'userBeans[{0}].name}, #'{'alarmInBeans[{0}].sex})");for (int i = 0; i < alarmInBeans.size(); i++) {// 将{0}替换为object数组的第一个元素sql.append(mf.format(new Object[] { i }));if (i < alarmInBeans.size() - 1) {sql.append(",");}}return sql.toString();
}