MyBatis動態(tài)SQL foreach標(biāo)簽實現(xiàn)批量插入的方法示例
需求:查出給定id的記錄:
<select resultType='comtestbeansEmployee'> SELECT * FROM tb1_emplyee WHERE id IN <foreach collection='list' item='item_id' separator=',' open='(' close=')'> #{item_id} </foreach> </select>
關(guān)于foreach標(biāo)簽,有幾個屬性應(yīng)該注意一下:
collection:指定要遍歷的集合: list類型的參數(shù)會特殊處理封裝在map中,map的key就叫l(wèi)ist item:將當(dāng)前遍歷出的元素賦值給指定的變量 separator:每個元素之間的分隔符 open:遍歷出所有結(jié)果拼接一個開始的字符 close:遍歷出所有結(jié)果拼接一個結(jié)束的字符 index:索引。遍歷list的時候是index就是索引,item就是當(dāng)前值 遍歷map的時候index表示的就是map的key,item就是map的值 #{變量名}就能取出變量的值也就是當(dāng)前遍歷出的元素測試方法:
@Test public void testDynamicSqlTest() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會自動提交數(shù)據(jù) SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); /*Employee employee=new Employee(1,'lili',null,'1');*/ List<Employee> emps=mappergetEmpsByConditionForeach(ArraysasList(1,2,3,4)); for (Employee e:emps){ Systemoutprintln(e); } } finally { openSessionclose(); } }
foreach標(biāo)簽也可以實現(xiàn)實現(xiàn)批量插入(刪除)數(shù)據(jù):
這里以批量插入數(shù)據(jù)為例:
<insert id='addEmps'> INSERT INTO tb1_emplyee(last_name,email,gender,d_id) VALUES <foreach collection='emps' item='emp' separator=','> (#{emplastName},#{empemail},#{empgender},#{empdeptid}) </foreach> </insert>
對應(yīng)的接口:
public void addEmps(@Param('emps')List<Employee> emps);
測試方法
@Test public void testBatchSave() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會自動提交數(shù)據(jù) SqlSession openSession = sqlSessionFactoryopenSession(); try { EmployeeMapperDymanicSQL mapper=openSessiongetMapper(EmployeeMapperDymanicSQLclass); List<Employee> emps=new ArrayList<Employee>(); 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(); } }
到此這篇關(guān)于MyBatis動態(tài)SQL foreach標(biāo)簽實現(xiàn)批量插入的方法示例的文章就介紹到這了,更多相關(guān)MyBatis動態(tài)SQL foreach批量插入內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在SQL Server 2005修改存儲過程2. mybatis中方法返回泛型與resultType不一致的解決3. SQL Server全文檢索簡介4. 服務(wù)器Centos部署MySql并連接Navicat過程詳解5. Oracle中pivot函數(shù)圖文實例詳解6. Docker部署Mysql集群的實現(xiàn)7. Oracle?Users表空間重命名問題解決8. MySQL 的啟動和連接方式實例分析9. SQL SERVER數(shù)據(jù)庫開發(fā)之存儲過程的應(yīng)用10. idea連接SQL Server數(shù)據(jù)庫的詳細(xì)圖文教程
