欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis注解方式 实现批量插入数据库

程序员文章站 2022-05-10 19:59:26
...

可以使用MyBatis的@InsertProvider注解

实现代码如下:

    @InsertProvider(type = CyQuestionDetailProvider.class, method = "batchInsertQuestionDetail")
    Integer batchInsertQuestionDetail(@Param("list")List<CyQuestionDetail> records);

    class CyQuestionDetailProvider {

        public String batchInsertQuestionDetail(Map<String, List<CyQuestionDetail>> map) {
            List<CyQuestionDetail> list = map.get("list");
            StringBuilder stringBuilder = new StringBuilder(256);
            stringBuilder.append("insert into test(QuesID, Type, Text, File, Age, Gender, CreateTime, XJFilePath) values");
            MessageFormat messageFormat = new MessageFormat("(#'{'list[{0}].quesId,jdbcType=INTEGER}, " +
                    "#'{'list[{0}].type,jdbcType=VARCHAR}, #'{'list[{0}].text,jdbcType=VARCHAR}, " +
                    "#'{'list[{0}].file,jdbcType=VARCHAR}, #'{'list[{0}].age,jdbcType=VARCHAR}, " +
                    "#'{'list[{0}].gender,jdbcType=VARCHAR},CURRENT_TIMESTAMP(), " +
                    "#'{'list[{0}].xjFilePath,jdbcType=VARCHAR})");
            for (int i = 0; i < list.size(); i++) {
                stringBuilder.append(messageFormat.format(new Integer[]{i}));
                stringBuilder.append(",");
            }
            stringBuilder.setLength(stringBuilder.length() - 1);
            return stringBuilder.toString();
        }

    }

 

转载于:https://my.oschina.net/niithub/blog/1837923