1接口
public boolean insertMembersBatch(@Param("memberList") List<Members> members);
@param参数别名
2.xml文件
<insert id="insertMembersBatch"> insert into members (member_name,pass_word,age) values <foreach collection="memberList" item="member" separator=","> (#{member.member_name},#{member.pass_word},#{member.age}) </foreach> </insert>
collection:参数别名
item:每个元素的名字
separator:元素之间的分割符号
3.测试
public static void main(String[] args) throws IOException { SqlSession session = getSqlSession(); try { // 面向接口方式 MemberMapperDynamicSQL mapper = session.getMapper(MemberMapperDynamicSQL.class); Members member1 = new Members(null, "老张", "123456", "25"); Members member2 = new Members(null, "老郑", "123456", "25"); Members member3 = new Members(null, "老李", "123456", "25"); List<Members> list = new ArrayList<Members>(); list.add(member1); list.add(member2); list.add(member3); mapper.insertMembersBatch(list); session.commit(); } finally { // 关闭session session.close(); } } public static SqlSession getSqlSession() throws IOException { // 读取全局配置文件 String resource = "conf/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 获取sqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 打开session SqlSession session = sqlSessionFactory.openSession(); return session; }
4.测试结果
==> Preparing: insert into members (member_name,pass_word,age) values (?,?,?) , (?,?,?) , (?,?,?) ==> Parameters: 老张(String), 123456(String), 25(String), 老郑(String), 123456(String), 25(String), 老李(String), 123456(String), 25(String) <== Updates: 3