mybaits xml 文件配置形式很容易写出来,官方也给出了例子,
例如:http://mybatis.github.io/mybatis-3/zh/dynamic-sql.html代码foreach动态sql就可以实现批量插入数据.
mybaits注解形式批量插入数据,就需要自己拼接成sql语句.
@InsertProvider(type = UserMapperProvider.class, method = "inserAll")
int insertAll(List<User> list);
public static class UserMapperProvider {
public String inserAll(Map<String, List<User>> map) {
List<User> list = map.get("list");
StringBuilder stringBuilder = new StringBuilder(256);
stringBuilder.append("insert into \"spring4_2015_user\" (\"loginName\", \"name\", \"password\", \"salt\",\"email\",\"status\",\"teamId\") values ");
MessageFormat messageFormat = new MessageFormat("(#'{'list[{0}].loginName},#'{'list[{0}].name},#'{'list[{0}].password},#'{'list[{0}].salt},#'{'list[{0}].email},#'{'list[{0}].status},#'{'list[{0}].teamId})");
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();
}
}
上述代码是H2数据库sql语句.当然mysql也支持这种批量插入数据.
来源:oschina
链接:https://my.oschina.net/u/2254200/blog/387679