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. MySQL基本調(diào)度策略淺析2. Mysql InnoDB的鎖定機(jī)制實(shí)例詳解3. Oracle 體系結(jié)構(gòu)介紹4. ORACLE中%TYPE和%ROWTYPE的使用詳解5. SQL SERVER偏移函數(shù)(LAG、LEAD、FIRST_VALUE、LAST _VALUE、NTH_VALUE)6. mysql數(shù)據(jù)表的基本操作之表結(jié)構(gòu)操作,字段操作實(shí)例分析7. MySQL中 concat函數(shù)的使用8. 數(shù)據(jù)庫(kù)Oracle9i的企業(yè)管理器簡(jiǎn)介9. MySQL分區(qū)的優(yōu)點(diǎn)10. MySQL數(shù)據(jù)庫(kù)入門之多實(shí)例配置方法詳解

網(wǎng)公網(wǎng)安備