MyBatis動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(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)簽,有幾個(gè)屬性應(yīng)該注意一下:
collection:指定要遍歷的集合: list類型的參數(shù)會(huì)特殊處理封裝在map中,map的key就叫l(wèi)ist item:將當(dāng)前遍歷出的元素賦值給指定的變量 separator:每個(gè)元素之間的分隔符 open:遍歷出所有結(jié)果拼接一個(gè)開始的字符 close:遍歷出所有結(jié)果拼接一個(gè)結(jié)束的字符 index:索引。遍歷list的時(shí)候是index就是索引,item就是當(dāng)前值 遍歷map的時(shí)候index表示的就是map的key,item就是map的值 #{變量名}就能取出變量的值也就是當(dāng)前遍歷出的元素測(cè)試方法:
@Test public void testDynamicSqlTest() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會(huì)自動(dòng)提交數(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)簽也可以實(shí)現(xiàn)實(shí)現(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>
對(duì)應(yīng)的接口:
public void addEmps(@Param('emps')List<Employee> emps);
測(cè)試方法
@Test public void testBatchSave() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); //1、獲取到的SqlSession不會(huì)自動(dòng)提交數(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動(dòng)態(tài)SQL foreach標(biāo)簽實(shí)現(xiàn)批量插入的方法示例的文章就介紹到這了,更多相關(guān)MyBatis動(dòng)態(tài)SQL foreach批量插入內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Microsoft Office Access修改代碼字體大小的方法2. 數(shù)據(jù)庫(kù)人員手冊(cè)之ORACLE應(yīng)用源碼3. DB2 XML 全文搜索之為文本搜索做準(zhǔn)備4. MySQL中InnoDB和MyISAM類型的差別5. 循序漸進(jìn)講解Oracle數(shù)據(jù)庫(kù)管理員的職責(zé)6. debian10 mariadb安裝過程詳解7. MySQL基礎(chǔ)教程9 —— 函數(shù)之日期和時(shí)間函數(shù)8. mssql鎖基礎(chǔ)教程9. MySQL 千萬級(jí)數(shù)據(jù)量如何快速分頁(yè)10. Mybatis查詢方法如何實(shí)現(xiàn)沒有返回值
