最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
MyBatis动态SQL foreach标签实现批量插入代码方法示例
时间:2020-06-15 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下MyBatis动态SQL foreach标签实现批量插入代码方法示例,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
需求:查出给定id的记录:
关于foreach标签,有几个属性应该注意一下:
collection:指定要遍历的集合:
pst类型的参数会特殊处理封装在map中,map的key就叫pst
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历pst的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素
测试方法:
@Test public void testDynamicSqlTest() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、获取到的SqlSession不会自动提交数据 SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); /*Employee employee=new Employee(1,"lili",null,"1");*/ Listemps=mappergetEmpsByConditionForeach(ArraysasList(1,2,3,4)); for (Employee e:emps){ Systemoutprintln(e); } } finally { openSessionclose(); } }
foreach标签也可以实现实现批量插入(删除)数据:
这里以批量插入数据为例:
INSERT INTO tb1_emplyee(last_name,email,gender,d_id) VALUES (#{emplastName},#{empemail},#{empgender},#{empdeptid})
对应的接口:
public void addEmps(@Param("emps")Listemps);
测试方法
@Test public void testBatchSave() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、获取到的SqlSession不会自动提交数据 SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); Listemps=new ArrayList (); empsadd(new Employee(null,"Eminem","Eminem@com","1",new Department(1))); empsadd(new Employee(null,"2Pac","2Pac@com","1",new Department(1))); mapperaddEmps(emps); openSessioncommit(); } finally { openSessionclose(); } }
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10