foreach 实现 MyBatis 遍历集合与批量操作数据
一、寫在前面
MyBatis 動態 SQL 的一個常用的操作需求是對一個集合進行遍歷,通常是在構建 IN 條件語句的時候。foreach允許你指定一個集合,聲明可以在元素體內使用的集合項(item)和索引(index)變量。foreach 是動態 SQL 中一個非常強大的標簽。下面就來體驗一下foreach 標簽帶來的便捷之處,有關批量操作的實現,這里以批量插入數據為例。
二、foreach遍歷傳遞進來的集合
有時候我們可能會有下面的需求,根據多個 id 查詢對應的信息,這多個 id 的數量是不固定的。
SELECT * FROM t_employee WHERE id IN (1, 2, 3, ...)這時候我們可以通過使用foreach標簽來遍歷集合中的參數,完成多個 id 之間的拼接。
mapper 接口:
/** 根據傳入的 id 集合,查詢出對應的員工信息,并使用集合保存信息 */List<Employee> getEmpsByConditions(@Param("list") List<Integer> idList);SQL 映射文件:
<!-- 注意返回的數據類型是集合中保存的數據類型 Employee--><select id="getEmpsByConditions" resultType="com.jas.mybatis.bean.Employee">SELECT * FROM t_employee WHERE id IN <!--collection:指定要遍歷的集合item:取出當前集合中元素,賦給 item 中的值separator:遍歷出的多個元素之間用什么分隔符分隔開open:遍歷集合前用什么字符進行拼接close:遍歷集合后用什么字符進行拼接在 foreach 標簽中還有一個屬性 index,遍歷集合的時候 index 表示的是當前元素的索引,item 對應索引中的值遍歷 map 的時候 index 表示的是當前 map 中的 key,item 是 key 對應的 value--><foreach collection="list" item="empId" separator="," open="(" close=")">#{empId}</foreach></select>測試代碼:
// 用于返回 SqlSession 對象private SqlSession getSqlSession() throws IOException {String resource = "mybatis-config.xml";InputStream is = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession = sqlSessionFactory.openSession();return sqlSession;}@Testpublic void testList() throws IOException {SqlSession sqlSession = getSqlSession();EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);List<Employee> list = employeeMapper.getEmpsByConditions(Arrays.asList(1,2,15));for(Employee employee : list){System.out.println(employee);}sqlSession.close();}執行結果:
三、foreach批量插入數據
實現foreach批量插入數據有兩種方法,一種是只發送一條 SQL,插入的多條數據之間通過”,” 分隔開,另一種方式是每插入一條數據就發送一條 SQL 語句,多個 SQL 語句之間用”;“分割。
3.1 一條 SQL 批量插入數據
mapper 接口:
/** 返回值為 Integer 類型 */Integer addEmpsByList(@Param("list") List<Employee> list);SQL 映射文件:
<insert id="addEmpsByList" parameterType="com.jas.mybatis.bean.Employee">INSERT INTO t_employee(username, gender, email) VALUES <foreach collection="list" item="emp" separator=",">(#{emp.username}, #{emp.gender}, #{emp.email})</foreach></insert>測試代碼:
@Testpublic void testBatchAdd() throws IOException {SqlSession sqlSession = getSqlSession();EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);List<Employee> List = new ArrayList<>();List.add(new Employee(null, "Jas", '1', "fsd54@qq.com"));List.add(new Employee(null, "Jason", '0', "456jhk@qq.com"));employeeMapper.addEmpsByList(List);sqlSession.commit();sqlSession.close();}執行結果:
3.2 執行多條 SQL 批量插入數據
修改對應的 SQL 映射文件中的 SQL:
<insert id="addEmpsByList" parameterType="com.jas.mybatis.bean.Employee"><!-- 每插入一條數據就執行一次 SQL,中間用";"分隔開 --><foreach collection="list" item="emp" separator=";">INSERT INTO t_employee(username, gender, email) VALUES (#{emp.username}, #{emp.gender}, #{emp.email})</foreach></insert>MySql 默認的情況下是不支持使用”;” 分隔開多條 SQL 進行執行的,需要設置一個連接屬性allowMultiQueries=true來支持。可以在連接數據庫的時候設置這個屬性。
jdbc.url=jdbc:mysql://localhost:3306/mybatis-study?allowMultiQueries=true測試代碼:
@Testpublic void testBatchAdd() throws IOException {SqlSession sqlSession = getSqlSession();EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);List<Employee> List = new ArrayList<>();List.add(new Employee(null, "Tom", '1', "fd@qq.com"));List.add(new Employee(null, "Tony", '0', "456fdfjhk@qq.com"));employeeMapper.addEmpsByList(List);sqlSession.commit();sqlSession.close();}執行結果:
四、總結
這篇博文主要對 MyBati 動態 SQL 中的foreach進行了介紹與其使用場景的應用,MyBatis 還提供了其他的標簽來支持動態 SQL。比如:if、choose (when, otherwise)、trim (where, set),有關的詳細信息可以到官方文檔進行深入了解,希望這篇博文能夠為你提供一些幫助。
動態 SQL 官方文檔鏈接:
http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html
總結
以上是生活随笔為你收集整理的foreach 实现 MyBatis 遍历集合与批量操作数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: e431怎么调u盘启动 &quo
- 下一篇: 浅谈MyBatis一级缓存