方式:
1.借助foreach标签使用 insert into table values() / select * from table where id in
<select id="getPersonByArray2" resultType="Person">
select * from person where id in
<foreach collection="要遍历的集合名称" item="id" index="i" open="(" close=")"
separator=",">
#{id}
</foreach>
</select>
2.借助MySQL数据库连接属性allowMultiQueries=true
<insert id="addPersons">
<foreach collection="要遍历的的集合别名" item="p" separator=";">
insert into person(username,email,gender) values
(#{p.username},#{p.email},#{p.gender})
</foreach>
</insert>
如果运行报下列错误:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into person(username,email,gender) values
('jerry1','email1',' at line 4
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: insert into person(username,email,gender) values (?,?,?) ; insert into person(username,email,gender) values (?,?,?) ; insert into person(username,email,gender) values (?,?,?) ; insert into person(username,email,gender) values (?,?,?) ; insert into person(username,email,gender) values (?,?,?)
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into person(username,email,gender) values
('jerry1','email1',' at line 4
在连接数据库的url后面加 allowMultiQueries=true
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"/>