foreach: 用于循环拼接的内置标签,常用于批量新增、in查询等常见
包含以下属性:
collection:必填,值为要迭代循环的集合类型,情况有多种
入参是List类型的时候,collection属性值为list
入参是Map类型的时候,collection 属性值为map的key值
item:每一个元素进行迭代时的别名
index:索引的属性名,在集合数组情况下值为当前索引值,当迭代对象是map时,这个值是
map的key
open:整个循环内容的开头字符串
close:整个循环内容的结尾字符串
separator: 每次循环的分隔符
代码:
VideoMapper.xml
<insert id="addBatch" parameterType="work.yspan.online_class.domain.Video" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into video (title, summary, cover_img, price, create_time,point)
values
<foreach collection="list" item="video" separator=",">
(#{video.title,jdbcType=VARCHAR},#{video.summary,jdbcType=VARCHAR},#{video.coverImg,jdbcType=VARCHAR},#{video.price,jdbcType=INTEGER },#{video.createTime,jdbcType=TIMESTAMP},#{video.point,jdbcType=DOUBLE })
</foreach>
</insert>
VideoMapper.java:
public interface VideoMapper {
/**
* 批量插入数据
*/
int addBatch(List<Video> list);
}
测试方法代码:
public class SqlSessionDemo {
public static void main(String [] args) throws IOException {
//读取配置文件
String resouce="config/mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resouce);
//构建Session工厂
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//获取Session
try(SqlSession sqlSession=sqlSessionFactory.openSession()){
VideoMapper videoMapper=sqlSession.getMapper(VideoMapper.class);
Video video1=new Video();
video1.setTitle("ssm1");
video1.setSummary("这是ssm课程1");
video1.setCoverImg("http://yspan.work:8232");
video1.setPrice(8811);
video1.setCreateTime(new Date());
video1.setPoint(8.1);
Video video2=new Video();
video2.setTitle("ssm2");
video2.setSummary("这是ssm课程2");
video2.setCoverImg("http://yspan.work:8232");
video2.setPrice(8822);
video2.setCreateTime(new Date());
video2.setPoint(8.2);
List<Video> list=new ArrayList<>();
list.add(video1);
list.add(video2);
int row=videoMapper.addBatch(list);
System.out.println(row);
System.out.println(list.toString());
}
}
}
效果截图: